@dizzlkheinz/ynab-mcpb 0.18.3 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (346) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/CLAUDE.md +87 -8
  3. package/bin/ynab-mcp-server.cjs +2 -2
  4. package/bin/ynab-mcp-server.js +3 -3
  5. package/biome.json +39 -0
  6. package/dist/bundle/index.cjs +67 -67
  7. package/dist/index.d.ts +1 -1
  8. package/dist/index.js +27 -27
  9. package/dist/server/YNABMCPServer.d.ts +3 -4
  10. package/dist/server/YNABMCPServer.js +111 -116
  11. package/dist/server/budgetResolver.d.ts +6 -5
  12. package/dist/server/budgetResolver.js +46 -36
  13. package/dist/server/cacheKeys.js +6 -6
  14. package/dist/server/cacheManager.js +14 -11
  15. package/dist/server/completions.d.ts +2 -2
  16. package/dist/server/completions.js +20 -15
  17. package/dist/server/config.d.ts +10 -5
  18. package/dist/server/config.js +24 -7
  19. package/dist/server/deltaCache.d.ts +2 -2
  20. package/dist/server/deltaCache.js +22 -16
  21. package/dist/server/deltaCache.merge.d.ts +2 -2
  22. package/dist/server/diagnostics.d.ts +4 -4
  23. package/dist/server/diagnostics.js +38 -32
  24. package/dist/server/errorHandler.d.ts +5 -12
  25. package/dist/server/errorHandler.js +219 -217
  26. package/dist/server/prompts.d.ts +2 -2
  27. package/dist/server/prompts.js +45 -45
  28. package/dist/server/rateLimiter.js +4 -4
  29. package/dist/server/requestLogger.d.ts +1 -1
  30. package/dist/server/requestLogger.js +40 -35
  31. package/dist/server/resources.d.ts +3 -3
  32. package/dist/server/resources.js +55 -52
  33. package/dist/server/responseFormatter.js +6 -6
  34. package/dist/server/securityMiddleware.d.ts +2 -2
  35. package/dist/server/securityMiddleware.js +22 -20
  36. package/dist/server/serverKnowledgeStore.js +1 -1
  37. package/dist/server/toolRegistry.d.ts +3 -3
  38. package/dist/server/toolRegistry.js +47 -40
  39. package/dist/tools/__tests__/deltaTestUtils.d.ts +3 -3
  40. package/dist/tools/__tests__/deltaTestUtils.js +2 -2
  41. package/dist/tools/accountTools.d.ts +9 -8
  42. package/dist/tools/accountTools.js +47 -47
  43. package/dist/tools/adapters.d.ts +13 -8
  44. package/dist/tools/adapters.js +21 -11
  45. package/dist/tools/budgetTools.d.ts +8 -7
  46. package/dist/tools/budgetTools.js +22 -22
  47. package/dist/tools/categoryTools.d.ts +9 -8
  48. package/dist/tools/categoryTools.js +68 -59
  49. package/dist/tools/compareTransactions/formatter.d.ts +3 -3
  50. package/dist/tools/compareTransactions/formatter.js +9 -9
  51. package/dist/tools/compareTransactions/index.d.ts +6 -6
  52. package/dist/tools/compareTransactions/index.js +58 -43
  53. package/dist/tools/compareTransactions/matcher.d.ts +1 -1
  54. package/dist/tools/compareTransactions/matcher.js +28 -15
  55. package/dist/tools/compareTransactions/parser.d.ts +2 -2
  56. package/dist/tools/compareTransactions/parser.js +144 -138
  57. package/dist/tools/compareTransactions/types.d.ts +4 -4
  58. package/dist/tools/compareTransactions.d.ts +1 -1
  59. package/dist/tools/compareTransactions.js +1 -1
  60. package/dist/tools/deltaFetcher.d.ts +2 -2
  61. package/dist/tools/deltaFetcher.js +16 -15
  62. package/dist/tools/deltaSupport.d.ts +4 -4
  63. package/dist/tools/deltaSupport.js +35 -41
  64. package/dist/tools/exportTransactions.d.ts +5 -4
  65. package/dist/tools/exportTransactions.js +61 -59
  66. package/dist/tools/monthTools.d.ts +7 -6
  67. package/dist/tools/monthTools.js +31 -29
  68. package/dist/tools/payeeTools.d.ts +7 -6
  69. package/dist/tools/payeeTools.js +28 -28
  70. package/dist/tools/reconcileAdapter.d.ts +2 -2
  71. package/dist/tools/reconcileAdapter.js +21 -11
  72. package/dist/tools/reconciliation/analyzer.d.ts +4 -4
  73. package/dist/tools/reconciliation/analyzer.js +136 -57
  74. package/dist/tools/reconciliation/csvParser.d.ts +3 -3
  75. package/dist/tools/reconciliation/csvParser.js +128 -104
  76. package/dist/tools/reconciliation/executor.d.ts +4 -4
  77. package/dist/tools/reconciliation/executor.js +148 -109
  78. package/dist/tools/reconciliation/index.d.ts +10 -10
  79. package/dist/tools/reconciliation/index.js +96 -83
  80. package/dist/tools/reconciliation/matcher.d.ts +3 -3
  81. package/dist/tools/reconciliation/matcher.js +17 -16
  82. package/dist/tools/reconciliation/payeeNormalizer.js +19 -8
  83. package/dist/tools/reconciliation/recommendationEngine.d.ts +1 -1
  84. package/dist/tools/reconciliation/recommendationEngine.js +40 -40
  85. package/dist/tools/reconciliation/reportFormatter.d.ts +2 -2
  86. package/dist/tools/reconciliation/reportFormatter.js +79 -54
  87. package/dist/tools/reconciliation/signDetector.d.ts +1 -1
  88. package/dist/tools/reconciliation/types.d.ts +19 -16
  89. package/dist/tools/reconciliation/ynabAdapter.d.ts +2 -2
  90. package/dist/tools/schemas/common.d.ts +1 -1
  91. package/dist/tools/schemas/common.js +1 -1
  92. package/dist/tools/schemas/outputs/accountOutputs.d.ts +1 -1
  93. package/dist/tools/schemas/outputs/accountOutputs.js +24 -18
  94. package/dist/tools/schemas/outputs/budgetOutputs.d.ts +1 -1
  95. package/dist/tools/schemas/outputs/budgetOutputs.js +14 -11
  96. package/dist/tools/schemas/outputs/categoryOutputs.d.ts +1 -1
  97. package/dist/tools/schemas/outputs/categoryOutputs.js +49 -29
  98. package/dist/tools/schemas/outputs/comparisonOutputs.d.ts +1 -1
  99. package/dist/tools/schemas/outputs/comparisonOutputs.js +12 -12
  100. package/dist/tools/schemas/outputs/index.d.ts +14 -14
  101. package/dist/tools/schemas/outputs/index.js +14 -14
  102. package/dist/tools/schemas/outputs/monthOutputs.d.ts +1 -1
  103. package/dist/tools/schemas/outputs/monthOutputs.js +56 -41
  104. package/dist/tools/schemas/outputs/payeeOutputs.d.ts +1 -1
  105. package/dist/tools/schemas/outputs/payeeOutputs.js +10 -10
  106. package/dist/tools/schemas/outputs/reconciliationOutputs.d.ts +2 -2
  107. package/dist/tools/schemas/outputs/reconciliationOutputs.js +45 -45
  108. package/dist/tools/schemas/outputs/transactionMutationOutputs.d.ts +1 -1
  109. package/dist/tools/schemas/outputs/transactionMutationOutputs.js +28 -22
  110. package/dist/tools/schemas/outputs/transactionOutputs.d.ts +1 -1
  111. package/dist/tools/schemas/outputs/transactionOutputs.js +43 -35
  112. package/dist/tools/schemas/outputs/utilityOutputs.d.ts +1 -1
  113. package/dist/tools/schemas/outputs/utilityOutputs.js +5 -3
  114. package/dist/tools/schemas/shared/commonOutputs.d.ts +1 -1
  115. package/dist/tools/schemas/shared/commonOutputs.js +15 -9
  116. package/dist/tools/transactionReadTools.d.ts +11 -0
  117. package/dist/tools/transactionReadTools.js +202 -0
  118. package/dist/tools/transactionSchemas.d.ts +309 -0
  119. package/dist/tools/transactionSchemas.js +235 -0
  120. package/dist/tools/transactionTools.d.ts +6 -302
  121. package/dist/tools/transactionTools.js +7 -2054
  122. package/dist/tools/transactionUtils.d.ts +31 -0
  123. package/dist/tools/transactionUtils.js +364 -0
  124. package/dist/tools/transactionWriteTools.d.ts +20 -0
  125. package/dist/tools/transactionWriteTools.js +1342 -0
  126. package/dist/tools/utilityTools.d.ts +5 -4
  127. package/dist/tools/utilityTools.js +11 -11
  128. package/dist/types/index.d.ts +7 -7
  129. package/dist/types/index.js +6 -6
  130. package/dist/types/reconciliation.d.ts +1 -1
  131. package/dist/types/toolRegistration.d.ts +14 -12
  132. package/dist/utils/amountUtils.js +1 -1
  133. package/dist/utils/dateUtils.js +4 -4
  134. package/dist/utils/errors.d.ts +3 -3
  135. package/dist/utils/errors.js +4 -4
  136. package/dist/utils/money.d.ts +2 -2
  137. package/dist/utils/money.js +8 -8
  138. package/dist/utils/validationError.d.ts +1 -1
  139. package/dist/utils/validationError.js +1 -1
  140. package/docs/assets/examples/reconciliation-with-recommendations.json +66 -66
  141. package/docs/assets/schemas/reconciliation-v2.json +360 -336
  142. package/docs/plans/2025-12-25-transaction-tools-refactor-design.md +211 -0
  143. package/docs/plans/2025-12-25-transaction-tools-refactor.md +905 -0
  144. package/esbuild.config.mjs +53 -50
  145. package/meta.json +12548 -12548
  146. package/package.json +98 -109
  147. package/scripts/analyze-bundle.mjs +33 -30
  148. package/scripts/create-pr-description.js +169 -120
  149. package/scripts/run-all-tests.js +205 -0
  150. package/scripts/run-domain-integration-tests.js +28 -18
  151. package/scripts/run-generate-mcpb.js +19 -17
  152. package/scripts/run-throttled-integration-tests.js +92 -83
  153. package/scripts/test-delta-params.mjs +149 -120
  154. package/scripts/test-recommendations.ts +36 -32
  155. package/scripts/tmpTransaction.ts +80 -43
  156. package/scripts/validate-env.js +98 -91
  157. package/scripts/verify-build.js +78 -76
  158. package/src/__tests__/comprehensive.integration.test.ts +1281 -1154
  159. package/src/__tests__/performance.test.ts +723 -671
  160. package/src/__tests__/setup.ts +442 -395
  161. package/src/__tests__/smoke.e2e.test.ts +41 -39
  162. package/src/__tests__/testRunner.ts +314 -295
  163. package/src/__tests__/testUtils.ts +456 -364
  164. package/src/__tests__/tools/reconciliation/csvParser.integration.test.ts +109 -107
  165. package/src/__tests__/tools/reconciliation/real-world.integration.test.ts +41 -41
  166. package/src/index.ts +68 -59
  167. package/src/server/CLAUDE.md +480 -0
  168. package/src/server/YNABMCPServer.ts +821 -794
  169. package/src/server/__tests__/YNABMCPServer.integration.test.ts +929 -893
  170. package/src/server/__tests__/YNABMCPServer.test.ts +903 -899
  171. package/src/server/__tests__/budgetResolver.test.ts +466 -423
  172. package/src/server/__tests__/cacheManager.test.ts +891 -874
  173. package/src/server/__tests__/completions.integration.test.ts +115 -106
  174. package/src/server/__tests__/completions.test.ts +334 -313
  175. package/src/server/__tests__/config.test.ts +98 -86
  176. package/src/server/__tests__/deltaCache.merge.test.ts +774 -703
  177. package/src/server/__tests__/deltaCache.swr.test.ts +198 -153
  178. package/src/server/__tests__/deltaCache.test.ts +946 -759
  179. package/src/server/__tests__/diagnostics.test.ts +825 -792
  180. package/src/server/__tests__/errorHandler.integration.test.ts +512 -462
  181. package/src/server/__tests__/errorHandler.test.ts +402 -397
  182. package/src/server/__tests__/prompts.test.ts +424 -347
  183. package/src/server/__tests__/rateLimiter.test.ts +313 -309
  184. package/src/server/__tests__/requestLogger.test.ts +443 -403
  185. package/src/server/__tests__/resources.template.test.ts +196 -185
  186. package/src/server/__tests__/resources.test.ts +294 -288
  187. package/src/server/__tests__/security.integration.test.ts +487 -421
  188. package/src/server/__tests__/securityMiddleware.test.ts +519 -444
  189. package/src/server/__tests__/server-startup.integration.test.ts +509 -490
  190. package/src/server/__tests__/serverKnowledgeStore.test.ts +174 -173
  191. package/src/server/__tests__/toolRegistration.test.ts +239 -210
  192. package/src/server/__tests__/toolRegistry.test.ts +907 -845
  193. package/src/server/budgetResolver.ts +221 -181
  194. package/src/server/cacheKeys.ts +6 -6
  195. package/src/server/cacheManager.ts +498 -484
  196. package/src/server/completions.ts +267 -243
  197. package/src/server/config.ts +35 -14
  198. package/src/server/deltaCache.merge.ts +146 -128
  199. package/src/server/deltaCache.ts +352 -309
  200. package/src/server/diagnostics.ts +257 -242
  201. package/src/server/errorHandler.ts +747 -744
  202. package/src/server/prompts.ts +181 -176
  203. package/src/server/rateLimiter.ts +131 -129
  204. package/src/server/requestLogger.ts +350 -322
  205. package/src/server/resources.ts +442 -374
  206. package/src/server/responseFormatter.ts +41 -37
  207. package/src/server/securityMiddleware.ts +223 -205
  208. package/src/server/serverKnowledgeStore.ts +67 -67
  209. package/src/server/toolRegistry.ts +508 -474
  210. package/src/tools/CLAUDE.md +604 -0
  211. package/src/tools/__tests__/accountTools.delta.integration.test.ts +128 -111
  212. package/src/tools/__tests__/accountTools.integration.test.ts +129 -111
  213. package/src/tools/__tests__/accountTools.test.ts +685 -638
  214. package/src/tools/__tests__/adapters.test.ts +142 -108
  215. package/src/tools/__tests__/budgetTools.delta.integration.test.ts +73 -73
  216. package/src/tools/__tests__/budgetTools.integration.test.ts +132 -124
  217. package/src/tools/__tests__/budgetTools.test.ts +442 -413
  218. package/src/tools/__tests__/categoryTools.delta.integration.test.ts +76 -68
  219. package/src/tools/__tests__/categoryTools.integration.test.ts +314 -288
  220. package/src/tools/__tests__/categoryTools.test.ts +656 -625
  221. package/src/tools/__tests__/compareTransactions/formatter.test.ts +535 -462
  222. package/src/tools/__tests__/compareTransactions/index.test.ts +378 -358
  223. package/src/tools/__tests__/compareTransactions/matcher.test.ts +497 -398
  224. package/src/tools/__tests__/compareTransactions/parser.test.ts +765 -747
  225. package/src/tools/__tests__/compareTransactions.test.ts +352 -332
  226. package/src/tools/__tests__/compareTransactions.window.test.ts +150 -146
  227. package/src/tools/__tests__/deltaFetcher.scheduled.integration.test.ts +69 -65
  228. package/src/tools/__tests__/deltaFetcher.test.ts +325 -265
  229. package/src/tools/__tests__/deltaSupport.test.ts +211 -184
  230. package/src/tools/__tests__/deltaTestUtils.ts +37 -33
  231. package/src/tools/__tests__/exportTransactions.test.ts +205 -200
  232. package/src/tools/__tests__/monthTools.delta.integration.test.ts +68 -68
  233. package/src/tools/__tests__/monthTools.integration.test.ts +178 -166
  234. package/src/tools/__tests__/monthTools.test.ts +561 -512
  235. package/src/tools/__tests__/payeeTools.delta.integration.test.ts +68 -68
  236. package/src/tools/__tests__/payeeTools.integration.test.ts +158 -142
  237. package/src/tools/__tests__/payeeTools.test.ts +486 -434
  238. package/src/tools/__tests__/transactionSchemas.test.ts +1204 -0
  239. package/src/tools/__tests__/transactionTools.integration.test.ts +875 -825
  240. package/src/tools/__tests__/transactionTools.test.ts +4923 -4366
  241. package/src/tools/__tests__/transactionUtils.test.ts +1016 -0
  242. package/src/tools/__tests__/utilityTools.integration.test.ts +32 -32
  243. package/src/tools/__tests__/utilityTools.test.ts +68 -58
  244. package/src/tools/accountTools.ts +293 -271
  245. package/src/tools/adapters.ts +120 -63
  246. package/src/tools/budgetTools.ts +121 -116
  247. package/src/tools/categoryTools.ts +379 -339
  248. package/src/tools/compareTransactions/formatter.ts +131 -119
  249. package/src/tools/compareTransactions/index.ts +249 -214
  250. package/src/tools/compareTransactions/matcher.ts +259 -209
  251. package/src/tools/compareTransactions/parser.ts +517 -487
  252. package/src/tools/compareTransactions/types.ts +38 -38
  253. package/src/tools/compareTransactions.ts +1 -1
  254. package/src/tools/deltaFetcher.ts +281 -260
  255. package/src/tools/deltaSupport.ts +264 -259
  256. package/src/tools/exportTransactions.ts +230 -218
  257. package/src/tools/monthTools.ts +180 -165
  258. package/src/tools/payeeTools.ts +152 -140
  259. package/src/tools/reconcileAdapter.ts +297 -246
  260. package/src/tools/reconciliation/CLAUDE.md +506 -0
  261. package/src/tools/reconciliation/__tests__/adapter.causes.test.ts +135 -112
  262. package/src/tools/reconciliation/__tests__/adapter.test.ts +249 -227
  263. package/src/tools/reconciliation/__tests__/analyzer.test.ts +408 -335
  264. package/src/tools/reconciliation/__tests__/csvParser.test.ts +71 -69
  265. package/src/tools/reconciliation/__tests__/executor.integration.test.ts +348 -323
  266. package/src/tools/reconciliation/__tests__/executor.progress.test.ts +503 -457
  267. package/src/tools/reconciliation/__tests__/executor.test.ts +898 -831
  268. package/src/tools/reconciliation/__tests__/matcher.test.ts +667 -663
  269. package/src/tools/reconciliation/__tests__/payeeNormalizer.test.ts +296 -276
  270. package/src/tools/reconciliation/__tests__/recommendationEngine.integration.test.ts +692 -624
  271. package/src/tools/reconciliation/__tests__/recommendationEngine.test.ts +1008 -986
  272. package/src/tools/reconciliation/__tests__/reconciliation.delta.integration.test.ts +187 -146
  273. package/src/tools/reconciliation/__tests__/reportFormatter.test.ts +583 -530
  274. package/src/tools/reconciliation/__tests__/scenarios/adapterCurrency.scenario.test.ts +75 -71
  275. package/src/tools/reconciliation/__tests__/scenarios/extremes.scenario.test.ts +70 -58
  276. package/src/tools/reconciliation/__tests__/scenarios/repeatAmount.scenario.test.ts +102 -88
  277. package/src/tools/reconciliation/__tests__/schemaUrl.test.ts +58 -43
  278. package/src/tools/reconciliation/__tests__/signDetector.test.ts +209 -206
  279. package/src/tools/reconciliation/__tests__/ynabAdapter.test.ts +66 -60
  280. package/src/tools/reconciliation/analyzer.ts +582 -406
  281. package/src/tools/reconciliation/csvParser.ts +656 -609
  282. package/src/tools/reconciliation/executor.ts +1290 -1128
  283. package/src/tools/reconciliation/index.ts +580 -528
  284. package/src/tools/reconciliation/matcher.ts +256 -240
  285. package/src/tools/reconciliation/payeeNormalizer.ts +92 -78
  286. package/src/tools/reconciliation/recommendationEngine.ts +357 -345
  287. package/src/tools/reconciliation/reportFormatter.ts +349 -276
  288. package/src/tools/reconciliation/signDetector.ts +89 -83
  289. package/src/tools/reconciliation/types.ts +164 -153
  290. package/src/tools/reconciliation/ynabAdapter.ts +17 -15
  291. package/src/tools/schemas/CLAUDE.md +546 -0
  292. package/src/tools/schemas/common.ts +1 -1
  293. package/src/tools/schemas/outputs/__tests__/accountOutputs.test.ts +410 -409
  294. package/src/tools/schemas/outputs/__tests__/budgetOutputs.test.ts +305 -299
  295. package/src/tools/schemas/outputs/__tests__/categoryOutputs.test.ts +431 -430
  296. package/src/tools/schemas/outputs/__tests__/comparisonOutputs.test.ts +510 -495
  297. package/src/tools/schemas/outputs/__tests__/dateValidation.test.ts +179 -153
  298. package/src/tools/schemas/outputs/__tests__/discrepancyDirection.test.ts +293 -254
  299. package/src/tools/schemas/outputs/__tests__/monthOutputs.test.ts +457 -457
  300. package/src/tools/schemas/outputs/__tests__/payeeOutputs.test.ts +362 -356
  301. package/src/tools/schemas/outputs/__tests__/reconciliationOutputs.test.ts +402 -399
  302. package/src/tools/schemas/outputs/__tests__/transactionMutationSchemas.test.ts +225 -211
  303. package/src/tools/schemas/outputs/__tests__/transactionOutputs.test.ts +457 -454
  304. package/src/tools/schemas/outputs/__tests__/utilityOutputs.test.ts +316 -315
  305. package/src/tools/schemas/outputs/accountOutputs.ts +40 -34
  306. package/src/tools/schemas/outputs/budgetOutputs.ts +24 -19
  307. package/src/tools/schemas/outputs/categoryOutputs.ts +76 -56
  308. package/src/tools/schemas/outputs/comparisonOutputs.ts +192 -169
  309. package/src/tools/schemas/outputs/index.ts +163 -163
  310. package/src/tools/schemas/outputs/monthOutputs.ts +95 -80
  311. package/src/tools/schemas/outputs/payeeOutputs.ts +18 -18
  312. package/src/tools/schemas/outputs/reconciliationOutputs.ts +386 -373
  313. package/src/tools/schemas/outputs/transactionMutationOutputs.ts +259 -231
  314. package/src/tools/schemas/outputs/transactionOutputs.ts +81 -71
  315. package/src/tools/schemas/outputs/utilityOutputs.ts +90 -84
  316. package/src/tools/schemas/shared/commonOutputs.ts +27 -19
  317. package/src/tools/toolCategories.ts +114 -114
  318. package/src/tools/transactionReadTools.ts +327 -0
  319. package/src/tools/transactionSchemas.ts +484 -0
  320. package/src/tools/transactionTools.ts +107 -2990
  321. package/src/tools/transactionUtils.ts +621 -0
  322. package/src/tools/transactionWriteTools.ts +2110 -0
  323. package/src/tools/utilityTools.ts +46 -41
  324. package/src/types/CLAUDE.md +477 -0
  325. package/src/types/__tests__/index.test.ts +51 -51
  326. package/src/types/index.ts +43 -39
  327. package/src/types/integration-tests.d.ts +26 -26
  328. package/src/types/reconciliation.ts +29 -29
  329. package/src/types/toolAnnotations.ts +30 -30
  330. package/src/types/toolRegistration.ts +43 -32
  331. package/src/utils/CLAUDE.md +508 -0
  332. package/src/utils/__tests__/dateUtils.test.ts +174 -168
  333. package/src/utils/__tests__/money.test.ts +193 -187
  334. package/src/utils/amountUtils.ts +5 -5
  335. package/src/utils/baseError.ts +5 -5
  336. package/src/utils/dateUtils.ts +29 -26
  337. package/src/utils/errors.ts +14 -14
  338. package/src/utils/money.ts +66 -52
  339. package/src/utils/validationError.ts +1 -1
  340. package/tsconfig.json +29 -29
  341. package/tsconfig.prod.json +16 -16
  342. package/vitest-reporters/split-json-reporter.ts +247 -204
  343. package/vitest.config.ts +99 -95
  344. package/.prettierignore +0 -10
  345. package/.prettierrc.json +0 -10
  346. package/eslint.config.js +0 -49
@@ -1,905 +1,909 @@
1
- import { describe, it, expect, vi, beforeEach, afterEach, beforeAll } from 'vitest';
2
- import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
3
-
4
- import { YNABMCPServer } from '../YNABMCPServer.js';
5
- import { AuthenticationError, ValidationError } from '../../types/index.js';
6
- import { ToolRegistry } from '../toolRegistry.js';
7
- import { cacheManager } from '../../server/cacheManager.js';
8
- import { responseFormatter } from '../../server/responseFormatter.js';
9
- import { createErrorHandler, ErrorHandler } from '../errorHandler.js';
10
-
11
- function parseCallToolJson<T = Record<string, unknown>>(result: CallToolResult): T {
12
- const text = result.content?.[0]?.text;
13
- const raw = typeof text === 'string' ? text : (JSON.stringify(text ?? {}) ?? '{}');
14
- return JSON.parse(raw) as T;
1
+ import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
2
+ import {
3
+ afterEach,
4
+ beforeAll,
5
+ beforeEach,
6
+ describe,
7
+ expect,
8
+ it,
9
+ vi,
10
+ } from "vitest";
11
+
12
+ import { cacheManager } from "../../server/cacheManager.js";
13
+ import { responseFormatter } from "../../server/responseFormatter.js";
14
+ import { AuthenticationError, ValidationError } from "../../types/index.js";
15
+ import { YNABMCPServer } from "../YNABMCPServer.js";
16
+ import { createErrorHandler } from "../errorHandler.js";
17
+ import type { ToolRegistry } from "../toolRegistry.js";
18
+
19
+ function parseCallToolJson<T = Record<string, unknown>>(
20
+ result: CallToolResult,
21
+ ): T {
22
+ const text = result.content?.[0]?.text;
23
+ const raw =
24
+ typeof text === "string" ? text : (JSON.stringify(text ?? {}) ?? "{}");
25
+ return JSON.parse(raw) as T;
15
26
  }
16
27
 
17
28
  /**
18
29
  * Real YNAB API tests using token from .env (YNAB_ACCESS_TOKEN)
19
30
  */
20
- describe('YNABMCPServer', () => {
21
- const originalEnv = process.env;
22
-
23
- // Shared constant for expected tool names
24
- const expectedToolNames = [
25
- 'list_budgets',
26
- 'get_budget',
27
- 'set_default_budget',
28
- 'get_default_budget',
29
- 'list_accounts',
30
- 'get_account',
31
- 'create_account',
32
- 'list_transactions',
33
- 'export_transactions',
34
- 'compare_transactions',
35
- 'reconcile_account',
36
- 'get_transaction',
37
- 'create_transaction',
38
- 'update_transaction',
39
- 'delete_transaction',
40
- 'list_categories',
41
- 'get_category',
42
- 'update_category',
43
- 'list_payees',
44
- 'get_payee',
45
- 'get_month',
46
- 'list_months',
47
- 'get_user',
48
- 'diagnostic_info',
49
- 'clear_cache',
50
- 'set_output_format',
51
- ] as const;
52
-
53
- beforeAll(() => {
54
- if (!process.env['YNAB_ACCESS_TOKEN']) {
55
- throw new Error(
56
- 'YNAB_ACCESS_TOKEN is required. Set it in your .env file to run integration tests.',
57
- );
58
- }
59
- });
60
-
61
- afterEach(() => {
62
- // Don't restore env completely, keep the API key loaded
63
- Object.keys(process.env).forEach((key) => {
64
- if (key !== 'YNAB_ACCESS_TOKEN' && key !== 'YNAB_BUDGET_ID') {
65
- if (originalEnv[key] !== undefined) {
66
- process.env[key] = originalEnv[key];
67
- } else {
68
- // Use Reflect.deleteProperty to avoid ESLint dynamic delete warning
69
- Reflect.deleteProperty(process.env, key);
70
- }
71
- }
72
- });
73
- });
74
-
75
- describe('Constructor and Environment Validation', () => {
76
- it('should create server instance with valid access token', () => {
77
- const server = new YNABMCPServer();
78
- expect(server).toBeInstanceOf(YNABMCPServer);
79
- expect(server.getYNABAPI()).toBeDefined();
80
- });
81
-
82
- it('should throw ValidationError when YNAB_ACCESS_TOKEN is missing', () => {
83
- const originalToken = process.env['YNAB_ACCESS_TOKEN'];
84
- delete process.env['YNAB_ACCESS_TOKEN'];
85
-
86
- expect(() => new YNABMCPServer()).toThrow(/YNAB_ACCESS_TOKEN/i);
87
-
88
- // Restore token
89
- process.env['YNAB_ACCESS_TOKEN'] = originalToken;
90
- });
91
-
92
- it('should throw ValidationError when YNAB_ACCESS_TOKEN is empty string', () => {
93
- const originalToken = process.env['YNAB_ACCESS_TOKEN'];
94
- process.env['YNAB_ACCESS_TOKEN'] = '';
95
-
96
- expect(() => new YNABMCPServer()).toThrow('YNAB_ACCESS_TOKEN must be a non-empty string');
97
-
98
- // Restore token
99
- process.env['YNAB_ACCESS_TOKEN'] = originalToken;
100
- });
101
-
102
- it('should throw ValidationError when YNAB_ACCESS_TOKEN is only whitespace', () => {
103
- const originalToken = process.env['YNAB_ACCESS_TOKEN'];
104
- process.env['YNAB_ACCESS_TOKEN'] = ' ';
105
-
106
- expect(() => new YNABMCPServer()).toThrow('YNAB_ACCESS_TOKEN must be a non-empty string');
107
-
108
- // Restore token
109
- process.env['YNAB_ACCESS_TOKEN'] = originalToken;
110
- });
111
-
112
- it('should reload configuration for each server instance', () => {
113
- const originalToken = process.env['YNAB_ACCESS_TOKEN'];
114
-
115
- process.env['YNAB_ACCESS_TOKEN'] = 'token-one';
116
- const firstServer = new YNABMCPServer(false);
117
- const firstConfig = (
118
- firstServer as unknown as { configInstance: { YNAB_ACCESS_TOKEN: string } }
119
- ).configInstance;
120
- expect(firstConfig.YNAB_ACCESS_TOKEN).toBe('token-one');
121
-
122
- process.env['YNAB_ACCESS_TOKEN'] = 'token-two';
123
- const secondServer = new YNABMCPServer(false);
124
- const secondConfig = (
125
- secondServer as unknown as { configInstance: { YNAB_ACCESS_TOKEN: string } }
126
- ).configInstance;
127
- expect(secondConfig.YNAB_ACCESS_TOKEN).toBe('token-two');
128
-
129
- process.env['YNAB_ACCESS_TOKEN'] = originalToken;
130
- });
131
-
132
- it('should trim whitespace from access token', () => {
133
- const originalToken = process.env['YNAB_ACCESS_TOKEN'];
134
- process.env['YNAB_ACCESS_TOKEN'] = ` ${originalToken} `;
135
-
136
- const server = new YNABMCPServer();
137
- expect(server).toBeInstanceOf(YNABMCPServer);
138
-
139
- // Restore token
140
- process.env['YNAB_ACCESS_TOKEN'] = originalToken;
141
- });
142
- });
143
-
144
- describe('Real YNAB API Integration', () => {
145
- let server: YNABMCPServer;
146
-
147
- beforeEach(() => {
148
- server = new YNABMCPServer(false); // Don't exit on error in tests
149
- });
150
-
151
- it('should successfully validate real YNAB token', async () => {
152
- const isValid = await server.validateToken();
153
- expect(isValid).toBe(true);
154
- });
155
-
156
- it('should successfully get user information', async () => {
157
- // Verify we can get user info
158
- const ynabAPI = server.getYNABAPI();
159
- const userResponse = await ynabAPI.user.getUser();
160
-
161
- expect(userResponse.data.user).toBeDefined();
162
- expect(userResponse.data.user.id).toBeDefined();
163
- console.warn(`✅ Connected to YNAB user: ${userResponse.data.user.id}`);
164
- });
165
-
166
- it('should successfully get budgets', async () => {
167
- const ynabAPI = server.getYNABAPI();
168
- const budgetsResponse = await ynabAPI.budgets.getBudgets();
169
-
170
- expect(budgetsResponse.data.budgets).toBeDefined();
171
- expect(Array.isArray(budgetsResponse.data.budgets)).toBe(true);
172
- expect(budgetsResponse.data.budgets.length).toBeGreaterThan(0);
173
-
174
- console.warn(`✅ Found ${budgetsResponse.data.budgets.length} budget(s)`);
175
- budgetsResponse.data.budgets.forEach((budget) => {
176
- console.warn(` - ${budget.name} (${budget.id})`);
177
- });
178
- });
179
-
180
- it('should handle invalid token gracefully', async () => {
181
- const originalToken = process.env['YNAB_ACCESS_TOKEN'];
182
- process.env['YNAB_ACCESS_TOKEN'] = 'invalid-token-format';
183
-
184
- try {
185
- const invalidServer = new YNABMCPServer(false);
186
- await expect(invalidServer.validateToken()).rejects.toThrow(AuthenticationError);
187
- } finally {
188
- // Restore original token
189
- process.env['YNAB_ACCESS_TOKEN'] = originalToken;
190
- }
191
- });
192
-
193
- it('should successfully start and connect MCP server', async () => {
194
- // This test verifies the full server startup process
195
- // Note: We can't fully test the stdio connection in a test environment,
196
- // but we can verify the server initializes without errors
197
-
198
- const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {
199
- // Mock implementation for testing
200
- });
201
-
202
- try {
203
- // The run method will validate the token and attempt to connect
204
- // In a test environment, the stdio connection will fail, but token validation should succeed
205
- await server.run();
206
- } catch (error) {
207
- // Expected to fail on stdio connection in test environment
208
- // But should not fail on token validation
209
- expect(error).not.toBeInstanceOf(AuthenticationError);
210
- expect(error).not.toBeInstanceOf(ValidationError);
211
- }
212
-
213
- consoleSpy.mockRestore();
214
- });
215
-
216
- it('should handle multiple rapid API calls without rate limiting issues', async () => {
217
- // Make multiple validation calls to test rate limiting behavior
218
- const promises = Array(3)
219
- .fill(null)
220
- .map(() => server.validateToken());
221
-
222
- // All should succeed (YNAB API is generally permissive for user info calls)
223
- const results = await Promise.all(promises);
224
- results.forEach((result) => expect(result).toBe(true));
225
- });
226
- });
227
-
228
- describe('MCP Server Functionality', () => {
229
- let server: YNABMCPServer;
230
- let registry: ToolRegistry;
231
-
232
- const accessToken = () => {
233
- const token = process.env['YNAB_ACCESS_TOKEN'];
234
- if (!token) {
235
- throw new Error('YNAB_ACCESS_TOKEN must be defined for integration tests');
236
- }
237
- return token;
238
- };
239
-
240
- const ensureDefaultBudget = async (): Promise<string> => {
241
- const budgetsResult = await registry.executeTool({
242
- name: 'list_budgets',
243
- accessToken: accessToken(),
244
- arguments: {},
245
- });
246
- const budgetsPayload = parseCallToolJson(budgetsResult);
247
- const firstBudget = budgetsPayload.budgets?.[0];
248
- expect(firstBudget?.id).toBeDefined();
249
-
250
- await registry.executeTool({
251
- name: 'set_default_budget',
252
- accessToken: accessToken(),
253
- arguments: { budget_id: firstBudget.id },
254
- });
255
-
256
- return firstBudget.id as string;
257
- };
258
-
259
- beforeEach(() => {
260
- server = new YNABMCPServer(false);
261
- registry = (server as unknown as { toolRegistry: ToolRegistry }).toolRegistry;
262
- });
263
-
264
- it('should expose the complete registered tool list via the registry', () => {
265
- const tools = registry.listTools();
266
- const names = tools.map((tool) => tool.name).sort();
267
- expect(names).toEqual([...expectedToolNames].sort());
268
- });
269
-
270
- it('should execute get_user tool via the registry', async () => {
271
- const result = await registry.executeTool({
272
- name: 'get_user',
273
- accessToken: accessToken(),
274
- arguments: {},
275
- });
276
- const payload = parseCallToolJson(result);
277
- expect(payload.user?.id).toBeDefined();
278
- });
279
-
280
- it('should set and retrieve default budget using tools', async () => {
281
- const budgetId = await ensureDefaultBudget();
282
-
283
- const defaultResult = await registry.executeTool({
284
- name: 'get_default_budget',
285
- accessToken: accessToken(),
286
- arguments: {},
287
- });
288
- const defaultPayload = parseCallToolJson(defaultResult);
289
- expect(defaultPayload.default_budget_id).toBe(budgetId);
290
- expect(defaultPayload.has_default).toBe(true);
291
- });
292
-
293
- it('should trigger cache warming after setting default budget', async () => {
294
- // Clear cache before test
295
- await registry.executeTool({
296
- name: 'clear_cache',
297
- accessToken: accessToken(),
298
- arguments: {},
299
- });
300
-
301
- const statsBeforeSet = cacheManager.getStats();
302
- const initialSize = statsBeforeSet.size;
303
-
304
- // Get a budget ID
305
- const budgetsResult = await registry.executeTool({
306
- name: 'list_budgets',
307
- accessToken: accessToken(),
308
- arguments: {},
309
- });
310
- const budgetsPayload = parseCallToolJson(budgetsResult);
311
- const firstBudget = budgetsPayload.budgets?.[0];
312
- expect(firstBudget?.id).toBeDefined();
313
-
314
- // Set default budget (this should trigger cache warming)
315
- await registry.executeTool({
316
- name: 'set_default_budget',
317
- accessToken: accessToken(),
318
- arguments: { budget_id: firstBudget.id },
319
- });
320
-
321
- // Wait for cache warming to complete with polling (it's fire-and-forget)
322
- const timeoutMs = 5000; // 5 second timeout
323
- const pollIntervalMs = 50; // Check every 50ms
324
- const startTime = Date.now();
325
- let statsAfterSet = cacheManager.getStats();
326
-
327
- while (statsAfterSet.size <= initialSize && Date.now() - startTime < timeoutMs) {
328
- await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
329
- statsAfterSet = cacheManager.getStats();
330
- }
331
-
332
- // Fail test if timeout was reached without cache growth
333
- if (statsAfterSet.size <= initialSize) {
334
- throw new Error(
335
- `Cache warming failed to complete within ${timeoutMs}ms. ` +
336
- `Initial size: ${initialSize}, Final size: ${statsAfterSet.size}`,
337
- );
338
- }
339
-
340
- // Cache should have more entries due to warming
341
- expect(statsAfterSet.size).toBeGreaterThan(initialSize);
342
-
343
- // Verify that common data types were cached
344
- const allKeys = cacheManager.getAllKeys();
345
- const hasAccountsCache = allKeys.some((key) => key.includes('accounts:list'));
346
- const hasCategoriesCache = allKeys.some((key) => key.includes('categories:list'));
347
- const hasPayeesCache = allKeys.some((key) => key.includes('payees:list'));
348
-
349
- // At least some cache warming should have occurred
350
- expect(hasAccountsCache || hasCategoriesCache || hasPayeesCache).toBe(true);
351
- });
352
-
353
- it('should handle cache warming errors gracefully', async () => {
354
- // Get a real budget ID first, since API validation is in place
355
- const budgetsResult = await registry.executeTool({
356
- name: 'list_budgets',
357
- accessToken: accessToken(),
358
- arguments: {},
359
- });
360
- const budgetsPayload = parseCallToolJson(budgetsResult);
361
- const firstBudget = budgetsPayload.budgets?.[0];
362
- expect(firstBudget?.id).toBeDefined();
363
- const realBudgetId = firstBudget.id as string;
364
-
365
- // This should succeed with API validation in place
366
- const result = await registry.executeTool({
367
- name: 'set_default_budget',
368
- accessToken: accessToken(),
369
- arguments: { budget_id: realBudgetId },
370
- });
371
-
372
- // The set_default_budget operation should succeed
373
- const payload = parseCallToolJson(result);
374
- expect(payload.message).toContain('Default budget set to:');
375
- expect(payload.default_budget_id).toBe(realBudgetId);
376
-
377
- // Wait a moment for cache warming attempts to complete
378
- await new Promise((resolve) => setTimeout(resolve, 100));
379
-
380
- // Server should still be functional
381
- const defaultResult = await registry.executeTool({
382
- name: 'get_default_budget',
383
- accessToken: accessToken(),
384
- arguments: {},
385
- });
386
- const defaultPayload = parseCallToolJson(defaultResult);
387
- expect(defaultPayload.default_budget_id).toBe(realBudgetId);
388
- });
389
-
390
- it('should execute list tools that rely on the default budget', async () => {
391
- await ensureDefaultBudget();
392
-
393
- const accountsResult = await registry.executeTool({
394
- name: 'list_accounts',
395
- accessToken: accessToken(),
396
- arguments: {},
397
- });
398
- const accountsPayload = parseCallToolJson(accountsResult);
399
- expect(Array.isArray(accountsPayload.accounts)).toBe(true);
400
-
401
- const categoriesResult = await registry.executeTool({
402
- name: 'list_categories',
403
- accessToken: accessToken(),
404
- arguments: {},
405
- });
406
- const categoriesPayload = parseCallToolJson(categoriesResult);
407
- expect(Array.isArray(categoriesPayload.categories)).toBe(true);
408
- });
409
-
410
- it('should provide diagnostic info with requested sections', async () => {
411
- const diagResult = await registry.executeTool({
412
- name: 'diagnostic_info',
413
- accessToken: accessToken(),
414
- arguments: {
415
- include_server: true,
416
- include_security: true,
417
- include_cache: true,
418
- include_memory: false,
419
- include_environment: false,
420
- },
421
- });
422
- const diagnostics = parseCallToolJson(diagResult);
423
- expect(diagnostics.timestamp).toBeDefined();
424
- expect(diagnostics.server).toBeDefined();
425
- expect(diagnostics.security).toBeDefined();
426
- expect(diagnostics.cache).toBeDefined();
427
- expect(diagnostics.memory).toBeUndefined();
428
- expect(diagnostics.environment).toBeUndefined();
429
- });
430
-
431
- it('should clear cache using the clear_cache tool', async () => {
432
- cacheManager.set('test:key', { value: 1 }, 1000);
433
- const statsBeforeClear = cacheManager.getStats();
434
- expect(statsBeforeClear.size).toBeGreaterThan(0);
435
-
436
- await registry.executeTool({
437
- name: 'clear_cache',
438
- accessToken: accessToken(),
439
- arguments: {},
440
- });
441
-
442
- const statsAfterClear = cacheManager.getStats();
443
- expect(statsAfterClear.size).toBe(0);
444
- expect(statsAfterClear.hits).toBe(0);
445
- expect(statsAfterClear.misses).toBe(0);
446
- expect(statsAfterClear.evictions).toBe(0);
447
- expect(statsAfterClear.lastCleanup).toBe(null);
448
- });
449
-
450
- it('should track cache hits and misses through tool execution', async () => {
451
- const initialStats = cacheManager.getStats();
452
- const initialHits = initialStats.hits;
453
-
454
- // Execute a tool that should use caching
455
- await registry.executeTool({
456
- name: 'list_budgets',
457
- accessToken: accessToken(),
458
- arguments: {},
459
- });
460
-
461
- const statsAfterFirstCall = cacheManager.getStats();
462
- expect(statsAfterFirstCall.size).toBeGreaterThan(initialStats.size);
463
-
464
- // Execute the same tool again - should hit cache
465
- await registry.executeTool({
466
- name: 'list_budgets',
467
- accessToken: accessToken(),
468
- arguments: {},
469
- });
470
-
471
- const statsAfterSecondCall = cacheManager.getStats();
472
- expect(statsAfterSecondCall.hits).toBeGreaterThan(initialHits);
473
- expect(statsAfterSecondCall.hitRate).toBeGreaterThan(0);
474
- });
475
-
476
- it('should respect maxEntries configuration from environment', () => {
477
- // Test that maxEntries is properly configured
478
- const stats = cacheManager.getStats();
479
- expect(stats.maxEntries).toEqual(expect.any(Number));
480
- expect(stats.maxEntries).toBeGreaterThan(0);
481
- });
482
-
483
- it('should surface enhanced cache metrics in diagnostics', async () => {
484
- // Generate some cache activity
485
- cacheManager.set('test:metric1', { data: 'value1' }, 1000);
486
- cacheManager.get('test:metric1'); // Hit
487
- cacheManager.get('test:nonexistent'); // Miss
488
-
489
- const result = await registry.executeTool({
490
- name: 'diagnostic_info',
491
- accessToken: accessToken(),
492
- arguments: {
493
- include_server: false,
494
- include_memory: false,
495
- include_environment: false,
496
- include_security: false,
497
- include_cache: true,
498
- },
499
- });
500
-
501
- const diagnostics = parseCallToolJson(result);
502
- expect(diagnostics.cache).toBeDefined();
503
- expect(diagnostics.cache.entries).toEqual(expect.any(Number));
504
- expect(diagnostics.cache.hits).toEqual(expect.any(Number));
505
- expect(diagnostics.cache.misses).toEqual(expect.any(Number));
506
- expect(diagnostics.cache.evictions).toEqual(expect.any(Number));
507
- expect(diagnostics.cache.maxEntries).toEqual(expect.any(Number));
508
- expect(diagnostics.cache.hitRate).toEqual(expect.stringMatching(/^\d+\.\d{2}%$/));
509
- expect(diagnostics.cache.performance_summary).toEqual(expect.any(String));
510
- });
511
-
512
- it('should configure output formatter via set_output_format tool', async () => {
513
- const baseline = responseFormatter.format({ probe: true });
514
-
515
- try {
516
- await registry.executeTool({
517
- name: 'set_output_format',
518
- accessToken: accessToken(),
519
- arguments: { default_minify: false, pretty_spaces: 4 },
520
- });
521
-
522
- const formatted = responseFormatter.format({ probe: true });
523
- expect(formatted).not.toBe(baseline);
524
- expect(formatted).toContain('\n');
525
- } finally {
526
- await registry.executeTool({
527
- name: 'set_output_format',
528
- accessToken: accessToken(),
529
- arguments: { default_minify: true, pretty_spaces: 2 },
530
- });
531
- }
532
- });
533
-
534
- it('should surface validation errors for invalid inputs', async () => {
535
- const result = await registry.executeTool({
536
- name: 'get_budget',
537
- accessToken: accessToken(),
538
- arguments: {} as Record<string, unknown>,
539
- });
540
- const payload = parseCallToolJson(result);
541
- expect(payload.error).toBeDefined();
542
- expect(payload.error.code).toBe('VALIDATION_ERROR');
543
- });
544
-
545
- describe('Budget Resolution Error Handling', () => {
546
- let freshServer: YNABMCPServer;
547
- let freshRegistry: ToolRegistry;
548
-
549
- beforeEach(() => {
550
- // Create a fresh server with no default budget set
551
- freshServer = new YNABMCPServer(false);
552
- freshRegistry = (freshServer as unknown as { toolRegistry: ToolRegistry }).toolRegistry;
553
- });
554
-
555
- const budgetDependentTools = [
556
- 'list_accounts',
557
- 'get_account',
558
- 'create_account',
559
- 'list_transactions',
560
- 'get_transaction',
561
- 'create_transaction',
562
- 'update_transaction',
563
- 'delete_transaction',
564
- 'list_categories',
565
- 'get_category',
566
- 'update_category',
567
- 'list_payees',
568
- 'get_payee',
569
- 'get_month',
570
- 'list_months',
571
- 'export_transactions',
572
- 'compare_transactions',
573
- 'reconcile_account',
574
- ] as const;
575
-
576
- budgetDependentTools.forEach((toolName) => {
577
- it(`should return standardized error for ${toolName} when no default budget is set`, async () => {
578
- const result = await freshRegistry.executeTool({
579
- name: toolName,
580
- accessToken: accessToken(),
581
- arguments: {},
582
- });
583
-
584
- const payload = parseCallToolJson(result);
585
- expect(payload.error).toBeDefined();
586
- expect(payload.error.code).toBe('VALIDATION_ERROR');
587
- expect(payload.error.message).toContain(
588
- 'No budget ID provided and no default budget set',
589
- );
590
- expect(payload.error.userMessage).toContain('invalid');
591
- expect(payload.error.suggestions).toBeDefined();
592
- expect(Array.isArray(payload.error.suggestions)).toBe(true);
593
- expect(
594
- payload.error.suggestions.some(
595
- (suggestion: string) =>
596
- suggestion.includes('set_default_budget') ||
597
- suggestion.includes('budget_id parameter'),
598
- ),
599
- ).toBe(true);
600
- });
601
- });
602
-
603
- it('should return standardized error for invalid budget ID format', async () => {
604
- const invalidBudgetId = 'not-a-valid-uuid';
605
- const result = await freshRegistry.executeTool({
606
- name: 'list_accounts',
607
- accessToken: accessToken(),
608
- arguments: { budget_id: invalidBudgetId },
609
- });
610
-
611
- const payload = parseCallToolJson(result);
612
- expect(payload.error).toBeDefined();
613
- expect(payload.error.code).toBe('VALIDATION_ERROR');
614
- expect(payload.error.message).toContain('Invalid budget ID format');
615
- expect(payload.error.userMessage).toContain('invalid');
616
- expect(payload.error.suggestions).toBeDefined();
617
- expect(Array.isArray(payload.error.suggestions)).toBe(true);
618
- expect(
619
- payload.error.suggestions.some(
620
- (suggestion: string) =>
621
- suggestion.includes('UUID v4 format') || suggestion.includes('list_budgets'),
622
- ),
623
- ).toBe(true);
624
- });
625
-
626
- it('should work normally after setting a default budget', async () => {
627
- // First, ensure we get the "no default budget" error
628
- let result = await freshRegistry.executeTool({
629
- name: 'list_accounts',
630
- accessToken: accessToken(),
631
- arguments: {},
632
- });
633
-
634
- let payload = parseCallToolJson(result);
635
- expect(payload.error).toBeDefined();
636
- expect(payload.error.code).toBe('VALIDATION_ERROR');
637
-
638
- // Now set a default budget
639
- const defaultBudgetId = await ensureDefaultBudget();
640
- await freshRegistry.executeTool({
641
- name: 'set_default_budget',
642
- accessToken: accessToken(),
643
- arguments: { budget_id: defaultBudgetId },
644
- });
645
-
646
- // Now the same call should work
647
- result = await freshRegistry.executeTool({
648
- name: 'list_accounts',
649
- accessToken: accessToken(),
650
- arguments: {},
651
- });
652
-
653
- payload = parseCallToolJson(result);
654
- // Should have accounts data or be valid response, not an error
655
- expect(payload.error).toBeUndefined();
656
- });
657
-
658
- it('should have consistent error response structure across all budget-dependent tools', async () => {
659
- const promises = budgetDependentTools.map((toolName) =>
660
- freshRegistry.executeTool({
661
- name: toolName,
662
- accessToken: accessToken(),
663
- arguments: {},
664
- }),
665
- );
666
-
667
- const results = await Promise.all(promises);
668
-
669
- results.forEach((result) => {
670
- const payload = parseCallToolJson(result);
671
-
672
- // All should have the same error structure
673
- expect(payload).toHaveProperty(
674
- 'error',
675
- expect.objectContaining({
676
- code: 'VALIDATION_ERROR',
677
- message: expect.stringContaining('No budget ID provided and no default budget set'),
678
- userMessage: expect.any(String),
679
- suggestions: expect.arrayContaining([
680
- expect.stringMatching(/set_default_budget|budget_id parameter/),
681
- ]),
682
- }),
683
- );
684
- });
685
- });
686
- });
687
- });
688
-
689
- describe('Modular Architecture Integration', () => {
690
- let server: YNABMCPServer;
691
-
692
- beforeEach(() => {
693
- server = new YNABMCPServer(false);
694
- });
695
-
696
- it('should initialize all service modules during construction', () => {
697
- // Verify the server has been constructed successfully with all modules
698
- expect(server).toBeInstanceOf(YNABMCPServer);
699
-
700
- // Check that core functionality from modules works through public interface
701
- expect(server.getYNABAPI()).toBeDefined();
702
- expect(server.getServer()).toBeDefined();
703
- });
704
-
705
- it('should use config module for environment validation', () => {
706
- // The fact that constructor succeeds means config module is working
707
- // This test verifies the integration is seamless
708
- expect(server.getYNABAPI()).toBeDefined();
709
- });
710
-
711
- it('should handle resource requests through resource manager', async () => {
712
- // Test that resources work (this goes through the resource manager now)
713
- const mcpServer = server.getServer();
714
- expect(mcpServer).toBeDefined();
715
-
716
- // The server should be properly configured with resource handlers
717
- // If the integration failed, the server wouldn't have the handlers
718
- expect(() => server.getYNABAPI()).not.toThrow();
719
- });
720
-
721
- it('should handle prompt requests through prompt manager', async () => {
722
- // Test that the server has prompt handling capability
723
- // The integration ensures prompt handlers are properly set up
724
- const mcpServer = server.getServer();
725
- expect(mcpServer).toBeDefined();
726
- });
727
-
728
- it('should handle diagnostic requests through diagnostic manager', async () => {
729
- // Test that diagnostic tools work through the tool registry integration
730
- const registry = (server as unknown as { toolRegistry: ToolRegistry }).toolRegistry;
731
-
732
- // Verify diagnostic tool is registered
733
- const tools = registry.listTools();
734
- const diagnosticTool = tools.find((tool) => tool.name === 'diagnostic_info');
735
- expect(diagnosticTool).toBeDefined();
736
- expect(diagnosticTool?.description).toContain('diagnostic information');
737
- });
738
-
739
- it('should maintain backward compatibility after modular refactoring', async () => {
740
- // Test that all expected tools are still available
741
- const registry = (server as unknown as { toolRegistry: ToolRegistry }).toolRegistry;
742
- const tools = registry.listTools();
743
-
744
- // Use the shared expectedToolNames constant defined at the top of the test file
745
-
746
- const actualToolNames = tools.map((tool) => tool.name).sort();
747
- expect(actualToolNames).toEqual(expectedToolNames.sort());
748
- });
749
-
750
- it('should maintain same error handling behavior after refactoring', () => {
751
- // Test that configuration errors are still properly thrown
752
- const originalToken = process.env['YNAB_ACCESS_TOKEN'];
753
- delete process.env['YNAB_ACCESS_TOKEN'];
754
-
755
- try {
756
- expect(() => new YNABMCPServer()).toThrow(/YNAB_ACCESS_TOKEN/i);
757
- } finally {
758
- // Restore token
759
- process.env['YNAB_ACCESS_TOKEN'] = originalToken;
760
- }
761
- });
762
-
763
- it('should delegate diagnostic collection to diagnostic manager', async () => {
764
- const registry = (server as unknown as { toolRegistry: ToolRegistry }).toolRegistry;
765
- const accessToken = process.env['YNAB_ACCESS_TOKEN']!;
766
-
767
- // Test that diagnostic_info tool works and returns expected structure
768
- const result = await registry.executeTool({
769
- name: 'diagnostic_info',
770
- accessToken,
771
- arguments: {
772
- include_server: true,
773
- include_memory: false,
774
- include_environment: false,
775
- include_security: false,
776
- include_cache: false,
777
- },
778
- });
779
-
780
- const diagnostics = parseCallToolJson(result);
781
- expect(diagnostics.timestamp).toBeDefined();
782
- expect(diagnostics.server).toBeDefined();
783
- expect(diagnostics.server.name).toBe('ynab-mcp-server');
784
- expect(diagnostics.server.version).toBeDefined();
785
-
786
- // These should be undefined because we set include flags to false
787
- expect(diagnostics.memory).toBeUndefined();
788
- expect(diagnostics.environment).toBeUndefined();
789
- expect(diagnostics.security).toBeUndefined();
790
- expect(diagnostics.cache).toBeUndefined();
791
- });
792
- });
793
-
794
- describe('Deprecated Methods', () => {
795
- let server: YNABMCPServer;
796
-
797
- beforeEach(() => {
798
- // Create server with valid token for testing deprecated method
799
- const originalToken = process.env['YNAB_ACCESS_TOKEN'];
800
- if (!originalToken) {
801
- throw new Error('YNAB_ACCESS_TOKEN must be defined for getBudgetId tests');
802
- }
803
- server = new YNABMCPServer(false);
804
- });
805
-
806
- describe('getBudgetId', () => {
807
- it('should throw ValidationError when no budget ID provided and no default set', () => {
808
- // Ensure no default budget is set
809
- expect(server.getDefaultBudget()).toBeUndefined();
810
-
811
- // Should throw ValidationError (not YNABAPIError)
812
- expect(() => {
813
- server.getBudgetId();
814
- }).toThrow(ValidationError);
815
-
816
- expect(() => {
817
- server.getBudgetId();
818
- }).toThrow('No budget ID provided and no default budget set');
819
- });
820
-
821
- it('should throw ValidationError for invalid budget ID format', () => {
822
- expect(() => {
823
- server.getBudgetId('invalid-id');
824
- }).toThrow(ValidationError);
825
-
826
- expect(() => {
827
- server.getBudgetId('invalid-id');
828
- }).toThrow(/Invalid budget ID format/);
829
- });
830
-
831
- it('should return valid budget ID when provided with valid UUID', () => {
832
- const validUuid = '123e4567-e89b-12d3-a456-426614174000';
833
- const result = server.getBudgetId(validUuid);
834
- expect(result).toBe(validUuid);
835
- });
836
- });
837
- });
838
-
839
- describe('ErrorHandler Integration', () => {
840
- let server: YNABMCPServer;
841
-
842
- beforeEach(() => {
843
- server = new YNABMCPServer(false);
844
- });
845
-
846
- it('should create ErrorHandler instance with responseFormatter', () => {
847
- // Verify that createErrorHandler was called with the formatter
848
- expect(server).toBeInstanceOf(YNABMCPServer);
849
-
850
- // The server should be successfully constructed with ErrorHandler injection
851
- expect(server.getYNABAPI()).toBeDefined();
852
- });
853
-
854
- it('should set global ErrorHandler formatter for backward compatibility', () => {
855
- // This test verifies that the global formatter was set
856
- // by checking that static ErrorHandler methods work
857
- const result = ErrorHandler.createValidationError('Test error');
858
-
859
- expect(result.content).toBeDefined();
860
- expect(result.content[0].type).toBe('text');
861
- expect(() => JSON.parse(result.content[0].text)).not.toThrow();
862
- });
863
-
864
- it('should use the same formatter for ErrorHandler and ToolRegistry', () => {
865
- // Verify that the server uses dependency injection correctly
866
- expect(server).toBeInstanceOf(YNABMCPServer);
867
-
868
- // The fact that the server constructs successfully means dependency injection worked
869
- // and both ErrorHandler and ToolRegistry are using the same formatter instance
870
- });
871
-
872
- it('should maintain existing error response format', async () => {
873
- const registry = (server as unknown as { toolRegistry: ToolRegistry }).toolRegistry;
874
-
875
- // Test that error responses still have the expected structure
876
- const result = await registry.executeTool({
877
- name: 'get_budget',
878
- accessToken: process.env['YNAB_ACCESS_TOKEN']!,
879
- arguments: {} as Record<string, unknown>,
880
- });
881
-
882
- const payload = parseCallToolJson(result);
883
- expect(payload.error).toBeDefined();
884
- expect(payload.error.code).toBe('VALIDATION_ERROR');
885
-
886
- // Verify the response is properly formatted JSON
887
- expect(() => JSON.parse(result.content[0].text)).not.toThrow();
888
- });
889
-
890
- it('should handle formatter consistency across static and instance methods', () => {
891
- const formatter = { format: (value: unknown) => JSON.stringify(value) };
892
- const errorHandler = createErrorHandler(formatter);
893
- ErrorHandler.setFormatter(formatter);
894
-
895
- const error = new ValidationError('Test error');
896
- const instanceResult = errorHandler.handleError(error, 'testing');
897
- const staticResult = ErrorHandler.handleError(error, 'testing');
898
-
899
- // Both should produce the same result structure
900
- expect(instanceResult.content[0].type).toBe(staticResult.content[0].type);
901
- expect(() => JSON.parse(instanceResult.content[0].text)).not.toThrow();
902
- expect(() => JSON.parse(staticResult.content[0].text)).not.toThrow();
903
- });
904
- });
31
+ describe("YNABMCPServer", () => {
32
+ const originalEnv = process.env;
33
+
34
+ // Shared constant for expected tool names
35
+ const expectedToolNames = [
36
+ "list_budgets",
37
+ "get_budget",
38
+ "set_default_budget",
39
+ "get_default_budget",
40
+ "list_accounts",
41
+ "get_account",
42
+ "create_account",
43
+ "list_transactions",
44
+ "export_transactions",
45
+ "compare_transactions",
46
+ "reconcile_account",
47
+ "get_transaction",
48
+ "create_transaction",
49
+ "update_transaction",
50
+ "delete_transaction",
51
+ "list_categories",
52
+ "get_category",
53
+ "update_category",
54
+ "list_payees",
55
+ "get_payee",
56
+ "get_month",
57
+ "list_months",
58
+ "get_user",
59
+ "diagnostic_info",
60
+ "clear_cache",
61
+ "set_output_format",
62
+ ] as const;
63
+
64
+ beforeAll(() => {
65
+ if (!process.env.YNAB_ACCESS_TOKEN) {
66
+ throw new Error(
67
+ "YNAB_ACCESS_TOKEN is required. Set it in your .env file to run integration tests.",
68
+ );
69
+ }
70
+ });
71
+
72
+ afterEach(() => {
73
+ // Don't restore env completely, keep the API key loaded
74
+ Object.keys(process.env).forEach((key) => {
75
+ if (key !== "YNAB_ACCESS_TOKEN" && key !== "YNAB_BUDGET_ID") {
76
+ if (originalEnv[key] !== undefined) {
77
+ process.env[key] = originalEnv[key];
78
+ } else {
79
+ // Use Reflect.deleteProperty to avoid ESLint dynamic delete warning
80
+ Reflect.deleteProperty(process.env, key);
81
+ }
82
+ }
83
+ });
84
+ });
85
+
86
+ describe("Constructor and Environment Validation", () => {
87
+ it("should create server instance with valid access token", () => {
88
+ const server = new YNABMCPServer();
89
+ expect(server).toBeInstanceOf(YNABMCPServer);
90
+ expect(server.getYNABAPI()).toBeDefined();
91
+ });
92
+
93
+ it("should throw ValidationError when YNAB_ACCESS_TOKEN is missing", () => {
94
+ const originalToken = process.env.YNAB_ACCESS_TOKEN;
95
+ process.env.YNAB_ACCESS_TOKEN = undefined;
96
+
97
+ expect(() => new YNABMCPServer()).toThrow(/YNAB_ACCESS_TOKEN/i);
98
+
99
+ // Restore token
100
+ process.env.YNAB_ACCESS_TOKEN = originalToken;
101
+ });
102
+
103
+ it("should throw ValidationError when YNAB_ACCESS_TOKEN is empty string", () => {
104
+ const originalToken = process.env.YNAB_ACCESS_TOKEN;
105
+ process.env.YNAB_ACCESS_TOKEN = "";
106
+
107
+ expect(() => new YNABMCPServer()).toThrow(
108
+ "YNAB_ACCESS_TOKEN must be a non-empty string",
109
+ );
110
+
111
+ // Restore token
112
+ process.env.YNAB_ACCESS_TOKEN = originalToken;
113
+ });
114
+
115
+ it("should throw ValidationError when YNAB_ACCESS_TOKEN is only whitespace", () => {
116
+ const originalToken = process.env.YNAB_ACCESS_TOKEN;
117
+ process.env.YNAB_ACCESS_TOKEN = " ";
118
+
119
+ expect(() => new YNABMCPServer()).toThrow(
120
+ "YNAB_ACCESS_TOKEN must be a non-empty string",
121
+ );
122
+
123
+ // Restore token
124
+ process.env.YNAB_ACCESS_TOKEN = originalToken;
125
+ });
126
+
127
+ it("should reload configuration for each server instance", () => {
128
+ const originalToken = process.env.YNAB_ACCESS_TOKEN;
129
+
130
+ process.env.YNAB_ACCESS_TOKEN = "token-one";
131
+ const firstServer = new YNABMCPServer(false);
132
+ const firstConfig = (
133
+ firstServer as unknown as {
134
+ configInstance: { YNAB_ACCESS_TOKEN: string };
135
+ }
136
+ ).configInstance;
137
+ expect(firstConfig.YNAB_ACCESS_TOKEN).toBe("token-one");
138
+
139
+ process.env.YNAB_ACCESS_TOKEN = "token-two";
140
+ const secondServer = new YNABMCPServer(false);
141
+ const secondConfig = (
142
+ secondServer as unknown as {
143
+ configInstance: { YNAB_ACCESS_TOKEN: string };
144
+ }
145
+ ).configInstance;
146
+ expect(secondConfig.YNAB_ACCESS_TOKEN).toBe("token-two");
147
+
148
+ process.env.YNAB_ACCESS_TOKEN = originalToken;
149
+ });
150
+
151
+ it("should trim whitespace from access token", () => {
152
+ const originalToken = process.env.YNAB_ACCESS_TOKEN;
153
+ process.env.YNAB_ACCESS_TOKEN = ` ${originalToken} `;
154
+
155
+ const server = new YNABMCPServer();
156
+ expect(server).toBeInstanceOf(YNABMCPServer);
157
+
158
+ // Restore token
159
+ process.env.YNAB_ACCESS_TOKEN = originalToken;
160
+ });
161
+ });
162
+
163
+ describe("Real YNAB API Integration", () => {
164
+ let server: YNABMCPServer;
165
+
166
+ beforeEach(() => {
167
+ server = new YNABMCPServer(false); // Don't exit on error in tests
168
+ });
169
+
170
+ it("should successfully validate real YNAB token", async () => {
171
+ const isValid = await server.validateToken();
172
+ expect(isValid).toBe(true);
173
+ });
174
+
175
+ it("should successfully get user information", async () => {
176
+ // Verify we can get user info
177
+ const ynabAPI = server.getYNABAPI();
178
+ const userResponse = await ynabAPI.user.getUser();
179
+
180
+ expect(userResponse.data.user).toBeDefined();
181
+ expect(userResponse.data.user.id).toBeDefined();
182
+ console.warn(`✅ Connected to YNAB user: ${userResponse.data.user.id}`);
183
+ });
184
+
185
+ it("should successfully get budgets", async () => {
186
+ const ynabAPI = server.getYNABAPI();
187
+ const budgetsResponse = await ynabAPI.budgets.getBudgets();
188
+
189
+ expect(budgetsResponse.data.budgets).toBeDefined();
190
+ expect(Array.isArray(budgetsResponse.data.budgets)).toBe(true);
191
+ expect(budgetsResponse.data.budgets.length).toBeGreaterThan(0);
192
+
193
+ console.warn(`✅ Found ${budgetsResponse.data.budgets.length} budget(s)`);
194
+ budgetsResponse.data.budgets.forEach((budget) => {
195
+ console.warn(` - ${budget.name} (${budget.id})`);
196
+ });
197
+ });
198
+
199
+ it("should handle invalid token gracefully", async () => {
200
+ const originalToken = process.env.YNAB_ACCESS_TOKEN;
201
+ process.env.YNAB_ACCESS_TOKEN = "invalid-token-format";
202
+
203
+ try {
204
+ const invalidServer = new YNABMCPServer(false);
205
+ await expect(invalidServer.validateToken()).rejects.toThrow(
206
+ AuthenticationError,
207
+ );
208
+ } finally {
209
+ // Restore original token
210
+ process.env.YNAB_ACCESS_TOKEN = originalToken;
211
+ }
212
+ });
213
+
214
+ it("should successfully start and connect MCP server", async () => {
215
+ // This test verifies the full server startup process
216
+ // Note: We can't fully test the stdio connection in a test environment,
217
+ // but we can verify the server initializes without errors
218
+
219
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {
220
+ // Mock implementation for testing
221
+ });
222
+
223
+ try {
224
+ // The run method will validate the token and attempt to connect
225
+ // In a test environment, the stdio connection will fail, but token validation should succeed
226
+ await server.run();
227
+ } catch (error) {
228
+ // Expected to fail on stdio connection in test environment
229
+ // But should not fail on token validation
230
+ expect(error).not.toBeInstanceOf(AuthenticationError);
231
+ expect(error).not.toBeInstanceOf(ValidationError);
232
+ }
233
+
234
+ consoleSpy.mockRestore();
235
+ });
236
+
237
+ it("should handle multiple rapid API calls without rate limiting issues", async () => {
238
+ // Make multiple validation calls to test rate limiting behavior
239
+ const promises = Array(3)
240
+ .fill(null)
241
+ .map(() => server.validateToken());
242
+
243
+ // All should succeed (YNAB API is generally permissive for user info calls)
244
+ const results = await Promise.all(promises);
245
+ results.forEach((result) => expect(result).toBe(true));
246
+ });
247
+ });
248
+
249
+ describe("MCP Server Functionality", () => {
250
+ let server: YNABMCPServer;
251
+ let registry: ToolRegistry;
252
+
253
+ const accessToken = () => {
254
+ const token = process.env.YNAB_ACCESS_TOKEN;
255
+ if (!token) {
256
+ throw new Error(
257
+ "YNAB_ACCESS_TOKEN must be defined for integration tests",
258
+ );
259
+ }
260
+ return token;
261
+ };
262
+
263
+ const ensureDefaultBudget = async (): Promise<string> => {
264
+ const budgetsResult = await registry.executeTool({
265
+ name: "list_budgets",
266
+ accessToken: accessToken(),
267
+ arguments: {},
268
+ });
269
+ const budgetsPayload = parseCallToolJson(budgetsResult);
270
+ const firstBudget = budgetsPayload.budgets?.[0];
271
+ expect(firstBudget?.id).toBeDefined();
272
+
273
+ await registry.executeTool({
274
+ name: "set_default_budget",
275
+ accessToken: accessToken(),
276
+ arguments: { budget_id: firstBudget.id },
277
+ });
278
+
279
+ return firstBudget.id as string;
280
+ };
281
+
282
+ beforeEach(() => {
283
+ server = new YNABMCPServer(false);
284
+ registry = (server as unknown as { toolRegistry: ToolRegistry })
285
+ .toolRegistry;
286
+ });
287
+
288
+ it("should expose the complete registered tool list via the registry", () => {
289
+ const tools = registry.listTools();
290
+ const names = tools.map((tool) => tool.name).sort();
291
+ expect(names).toEqual([...expectedToolNames].sort());
292
+ });
293
+
294
+ it("should execute get_user tool via the registry", async () => {
295
+ const result = await registry.executeTool({
296
+ name: "get_user",
297
+ accessToken: accessToken(),
298
+ arguments: {},
299
+ });
300
+ const payload = parseCallToolJson(result);
301
+ expect(payload.user?.id).toBeDefined();
302
+ });
303
+
304
+ it("should set and retrieve default budget using tools", async () => {
305
+ const budgetId = await ensureDefaultBudget();
306
+
307
+ const defaultResult = await registry.executeTool({
308
+ name: "get_default_budget",
309
+ accessToken: accessToken(),
310
+ arguments: {},
311
+ });
312
+ const defaultPayload = parseCallToolJson(defaultResult);
313
+ expect(defaultPayload.default_budget_id).toBe(budgetId);
314
+ expect(defaultPayload.has_default).toBe(true);
315
+ });
316
+
317
+ it("should trigger cache warming after setting default budget", async () => {
318
+ // Clear cache before test
319
+ await registry.executeTool({
320
+ name: "clear_cache",
321
+ accessToken: accessToken(),
322
+ arguments: {},
323
+ });
324
+
325
+ const statsBeforeSet = cacheManager.getStats();
326
+ const initialSize = statsBeforeSet.size;
327
+
328
+ // Get a budget ID
329
+ const budgetsResult = await registry.executeTool({
330
+ name: "list_budgets",
331
+ accessToken: accessToken(),
332
+ arguments: {},
333
+ });
334
+ const budgetsPayload = parseCallToolJson(budgetsResult);
335
+ const firstBudget = budgetsPayload.budgets?.[0];
336
+ expect(firstBudget?.id).toBeDefined();
337
+
338
+ // Set default budget (this should trigger cache warming)
339
+ await registry.executeTool({
340
+ name: "set_default_budget",
341
+ accessToken: accessToken(),
342
+ arguments: { budget_id: firstBudget.id },
343
+ });
344
+
345
+ // Wait for cache warming to complete with polling (it's fire-and-forget)
346
+ const timeoutMs = 5000; // 5 second timeout
347
+ const pollIntervalMs = 50; // Check every 50ms
348
+ const startTime = Date.now();
349
+ let statsAfterSet = cacheManager.getStats();
350
+
351
+ while (
352
+ statsAfterSet.size <= initialSize &&
353
+ Date.now() - startTime < timeoutMs
354
+ ) {
355
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
356
+ statsAfterSet = cacheManager.getStats();
357
+ }
358
+
359
+ // Fail test if timeout was reached without cache growth
360
+ if (statsAfterSet.size <= initialSize) {
361
+ throw new Error(
362
+ `Cache warming failed to complete within ${timeoutMs}ms. ` +
363
+ `Initial size: ${initialSize}, Final size: ${statsAfterSet.size}`,
364
+ );
365
+ }
366
+
367
+ // Cache should have more entries due to warming
368
+ expect(statsAfterSet.size).toBeGreaterThan(initialSize);
369
+
370
+ // Verify that common data types were cached
371
+ const allKeys = cacheManager.getAllKeys();
372
+ const hasAccountsCache = allKeys.some((key) =>
373
+ key.includes("accounts:list"),
374
+ );
375
+ const hasCategoriesCache = allKeys.some((key) =>
376
+ key.includes("categories:list"),
377
+ );
378
+ const hasPayeesCache = allKeys.some((key) => key.includes("payees:list"));
379
+
380
+ // At least some cache warming should have occurred
381
+ expect(hasAccountsCache || hasCategoriesCache || hasPayeesCache).toBe(
382
+ true,
383
+ );
384
+ });
385
+
386
+ it("should handle cache warming errors gracefully", async () => {
387
+ // Get a real budget ID first, since API validation is in place
388
+ const budgetsResult = await registry.executeTool({
389
+ name: "list_budgets",
390
+ accessToken: accessToken(),
391
+ arguments: {},
392
+ });
393
+ const budgetsPayload = parseCallToolJson(budgetsResult);
394
+ const firstBudget = budgetsPayload.budgets?.[0];
395
+ expect(firstBudget?.id).toBeDefined();
396
+ const realBudgetId = firstBudget.id as string;
397
+
398
+ // This should succeed with API validation in place
399
+ const result = await registry.executeTool({
400
+ name: "set_default_budget",
401
+ accessToken: accessToken(),
402
+ arguments: { budget_id: realBudgetId },
403
+ });
404
+
405
+ // The set_default_budget operation should succeed
406
+ const payload = parseCallToolJson(result);
407
+ expect(payload.message).toContain("Default budget set to:");
408
+ expect(payload.default_budget_id).toBe(realBudgetId);
409
+
410
+ // Wait a moment for cache warming attempts to complete
411
+ await new Promise((resolve) => setTimeout(resolve, 100));
412
+
413
+ // Server should still be functional
414
+ const defaultResult = await registry.executeTool({
415
+ name: "get_default_budget",
416
+ accessToken: accessToken(),
417
+ arguments: {},
418
+ });
419
+ const defaultPayload = parseCallToolJson(defaultResult);
420
+ expect(defaultPayload.default_budget_id).toBe(realBudgetId);
421
+ });
422
+
423
+ it("should execute list tools that rely on the default budget", async () => {
424
+ await ensureDefaultBudget();
425
+
426
+ const accountsResult = await registry.executeTool({
427
+ name: "list_accounts",
428
+ accessToken: accessToken(),
429
+ arguments: {},
430
+ });
431
+ const accountsPayload = parseCallToolJson(accountsResult);
432
+ expect(Array.isArray(accountsPayload.accounts)).toBe(true);
433
+
434
+ const categoriesResult = await registry.executeTool({
435
+ name: "list_categories",
436
+ accessToken: accessToken(),
437
+ arguments: {},
438
+ });
439
+ const categoriesPayload = parseCallToolJson(categoriesResult);
440
+ expect(Array.isArray(categoriesPayload.categories)).toBe(true);
441
+ });
442
+
443
+ it("should provide diagnostic info with requested sections", async () => {
444
+ const diagResult = await registry.executeTool({
445
+ name: "diagnostic_info",
446
+ accessToken: accessToken(),
447
+ arguments: {
448
+ include_server: true,
449
+ include_security: true,
450
+ include_cache: true,
451
+ include_memory: false,
452
+ include_environment: false,
453
+ },
454
+ });
455
+ const diagnostics = parseCallToolJson(diagResult);
456
+ expect(diagnostics.timestamp).toBeDefined();
457
+ expect(diagnostics.server).toBeDefined();
458
+ expect(diagnostics.security).toBeDefined();
459
+ expect(diagnostics.cache).toBeDefined();
460
+ expect(diagnostics.memory).toBeUndefined();
461
+ expect(diagnostics.environment).toBeUndefined();
462
+ });
463
+
464
+ it("should clear cache using the clear_cache tool", async () => {
465
+ cacheManager.set("test:key", { value: 1 }, 1000);
466
+ const statsBeforeClear = cacheManager.getStats();
467
+ expect(statsBeforeClear.size).toBeGreaterThan(0);
468
+
469
+ await registry.executeTool({
470
+ name: "clear_cache",
471
+ accessToken: accessToken(),
472
+ arguments: {},
473
+ });
474
+
475
+ const statsAfterClear = cacheManager.getStats();
476
+ expect(statsAfterClear.size).toBe(0);
477
+ expect(statsAfterClear.hits).toBe(0);
478
+ expect(statsAfterClear.misses).toBe(0);
479
+ expect(statsAfterClear.evictions).toBe(0);
480
+ expect(statsAfterClear.lastCleanup).toBe(null);
481
+ });
482
+
483
+ it("should track cache hits and misses through tool execution", async () => {
484
+ const initialStats = cacheManager.getStats();
485
+ const initialHits = initialStats.hits;
486
+
487
+ // Execute a tool that should use caching
488
+ await registry.executeTool({
489
+ name: "list_budgets",
490
+ accessToken: accessToken(),
491
+ arguments: {},
492
+ });
493
+
494
+ const statsAfterFirstCall = cacheManager.getStats();
495
+ expect(statsAfterFirstCall.size).toBeGreaterThan(initialStats.size);
496
+
497
+ // Execute the same tool again - should hit cache
498
+ await registry.executeTool({
499
+ name: "list_budgets",
500
+ accessToken: accessToken(),
501
+ arguments: {},
502
+ });
503
+
504
+ const statsAfterSecondCall = cacheManager.getStats();
505
+ expect(statsAfterSecondCall.hits).toBeGreaterThan(initialHits);
506
+ expect(statsAfterSecondCall.hitRate).toBeGreaterThan(0);
507
+ });
508
+
509
+ it("should respect maxEntries configuration from environment", () => {
510
+ // Test that maxEntries is properly configured
511
+ const stats = cacheManager.getStats();
512
+ expect(stats.maxEntries).toEqual(expect.any(Number));
513
+ expect(stats.maxEntries).toBeGreaterThan(0);
514
+ });
515
+
516
+ it("should surface enhanced cache metrics in diagnostics", async () => {
517
+ // Generate some cache activity
518
+ cacheManager.set("test:metric1", { data: "value1" }, 1000);
519
+ cacheManager.get("test:metric1"); // Hit
520
+ cacheManager.get("test:nonexistent"); // Miss
521
+
522
+ const result = await registry.executeTool({
523
+ name: "diagnostic_info",
524
+ accessToken: accessToken(),
525
+ arguments: {
526
+ include_server: false,
527
+ include_memory: false,
528
+ include_environment: false,
529
+ include_security: false,
530
+ include_cache: true,
531
+ },
532
+ });
533
+
534
+ const diagnostics = parseCallToolJson(result);
535
+ expect(diagnostics.cache).toBeDefined();
536
+ expect(diagnostics.cache.entries).toEqual(expect.any(Number));
537
+ expect(diagnostics.cache.hits).toEqual(expect.any(Number));
538
+ expect(diagnostics.cache.misses).toEqual(expect.any(Number));
539
+ expect(diagnostics.cache.evictions).toEqual(expect.any(Number));
540
+ expect(diagnostics.cache.maxEntries).toEqual(expect.any(Number));
541
+ expect(diagnostics.cache.hitRate).toEqual(
542
+ expect.stringMatching(/^\d+\.\d{2}%$/),
543
+ );
544
+ expect(diagnostics.cache.performance_summary).toEqual(expect.any(String));
545
+ });
546
+
547
+ it("should configure output formatter via set_output_format tool", async () => {
548
+ const baseline = responseFormatter.format({ probe: true });
549
+
550
+ try {
551
+ await registry.executeTool({
552
+ name: "set_output_format",
553
+ accessToken: accessToken(),
554
+ arguments: { default_minify: false, pretty_spaces: 4 },
555
+ });
556
+
557
+ const formatted = responseFormatter.format({ probe: true });
558
+ expect(formatted).not.toBe(baseline);
559
+ expect(formatted).toContain("\n");
560
+ } finally {
561
+ await registry.executeTool({
562
+ name: "set_output_format",
563
+ accessToken: accessToken(),
564
+ arguments: { default_minify: true, pretty_spaces: 2 },
565
+ });
566
+ }
567
+ });
568
+
569
+ it("should surface validation errors for invalid inputs", async () => {
570
+ const result = await registry.executeTool({
571
+ name: "get_budget",
572
+ accessToken: accessToken(),
573
+ arguments: {} as Record<string, unknown>,
574
+ });
575
+ const payload = parseCallToolJson(result);
576
+ expect(payload.error).toBeDefined();
577
+ expect(payload.error.code).toBe("VALIDATION_ERROR");
578
+ });
579
+
580
+ describe("Budget Resolution Error Handling", () => {
581
+ let freshServer: YNABMCPServer;
582
+ let freshRegistry: ToolRegistry;
583
+
584
+ beforeEach(() => {
585
+ // Create a fresh server with no default budget set
586
+ freshServer = new YNABMCPServer(false);
587
+ freshRegistry = (
588
+ freshServer as unknown as { toolRegistry: ToolRegistry }
589
+ ).toolRegistry;
590
+ });
591
+
592
+ const budgetDependentTools = [
593
+ "list_accounts",
594
+ "get_account",
595
+ "create_account",
596
+ "list_transactions",
597
+ "get_transaction",
598
+ "create_transaction",
599
+ "update_transaction",
600
+ "delete_transaction",
601
+ "list_categories",
602
+ "get_category",
603
+ "update_category",
604
+ "list_payees",
605
+ "get_payee",
606
+ "get_month",
607
+ "list_months",
608
+ "export_transactions",
609
+ "compare_transactions",
610
+ "reconcile_account",
611
+ ] as const;
612
+
613
+ budgetDependentTools.forEach((toolName) => {
614
+ it(`should return standardized error for ${toolName} when no default budget is set`, async () => {
615
+ const result = await freshRegistry.executeTool({
616
+ name: toolName,
617
+ accessToken: accessToken(),
618
+ arguments: {},
619
+ });
620
+
621
+ const payload = parseCallToolJson(result);
622
+ expect(payload.error).toBeDefined();
623
+ expect(payload.error.code).toBe("VALIDATION_ERROR");
624
+ expect(payload.error.message).toContain(
625
+ "No budget ID provided and no default budget set",
626
+ );
627
+ expect(payload.error.userMessage).toContain("invalid");
628
+ expect(payload.error.suggestions).toBeDefined();
629
+ expect(Array.isArray(payload.error.suggestions)).toBe(true);
630
+ expect(
631
+ payload.error.suggestions.some(
632
+ (suggestion: string) =>
633
+ suggestion.includes("set_default_budget") ||
634
+ suggestion.includes("budget_id parameter"),
635
+ ),
636
+ ).toBe(true);
637
+ });
638
+ });
639
+
640
+ it("should return standardized error for invalid budget ID format", async () => {
641
+ const invalidBudgetId = "not-a-valid-uuid";
642
+ const result = await freshRegistry.executeTool({
643
+ name: "list_accounts",
644
+ accessToken: accessToken(),
645
+ arguments: { budget_id: invalidBudgetId },
646
+ });
647
+
648
+ const payload = parseCallToolJson(result);
649
+ expect(payload.error).toBeDefined();
650
+ expect(payload.error.code).toBe("VALIDATION_ERROR");
651
+ expect(payload.error.message).toContain("Invalid budget ID format");
652
+ expect(payload.error.userMessage).toContain("invalid");
653
+ expect(payload.error.suggestions).toBeDefined();
654
+ expect(Array.isArray(payload.error.suggestions)).toBe(true);
655
+ expect(
656
+ payload.error.suggestions.some(
657
+ (suggestion: string) =>
658
+ suggestion.includes("UUID v4 format") ||
659
+ suggestion.includes("list_budgets"),
660
+ ),
661
+ ).toBe(true);
662
+ });
663
+
664
+ it("should work normally after setting a default budget", async () => {
665
+ // First, ensure we get the "no default budget" error
666
+ let result = await freshRegistry.executeTool({
667
+ name: "list_accounts",
668
+ accessToken: accessToken(),
669
+ arguments: {},
670
+ });
671
+
672
+ let payload = parseCallToolJson(result);
673
+ expect(payload.error).toBeDefined();
674
+ expect(payload.error.code).toBe("VALIDATION_ERROR");
675
+
676
+ // Now set a default budget
677
+ const defaultBudgetId = await ensureDefaultBudget();
678
+ await freshRegistry.executeTool({
679
+ name: "set_default_budget",
680
+ accessToken: accessToken(),
681
+ arguments: { budget_id: defaultBudgetId },
682
+ });
683
+
684
+ // Now the same call should work
685
+ result = await freshRegistry.executeTool({
686
+ name: "list_accounts",
687
+ accessToken: accessToken(),
688
+ arguments: {},
689
+ });
690
+
691
+ payload = parseCallToolJson(result);
692
+ // Should have accounts data or be valid response, not an error
693
+ expect(payload.error).toBeUndefined();
694
+ });
695
+
696
+ it("should have consistent error response structure across all budget-dependent tools", async () => {
697
+ const promises = budgetDependentTools.map((toolName) =>
698
+ freshRegistry.executeTool({
699
+ name: toolName,
700
+ accessToken: accessToken(),
701
+ arguments: {},
702
+ }),
703
+ );
704
+
705
+ const results = await Promise.all(promises);
706
+
707
+ results.forEach((result) => {
708
+ const payload = parseCallToolJson(result);
709
+
710
+ // All should have the same error structure
711
+ expect(payload).toHaveProperty(
712
+ "error",
713
+ expect.objectContaining({
714
+ code: "VALIDATION_ERROR",
715
+ message: expect.stringContaining(
716
+ "No budget ID provided and no default budget set",
717
+ ),
718
+ userMessage: expect.any(String),
719
+ suggestions: expect.arrayContaining([
720
+ expect.stringMatching(/set_default_budget|budget_id parameter/),
721
+ ]),
722
+ }),
723
+ );
724
+ });
725
+ });
726
+ });
727
+ });
728
+
729
+ describe("Modular Architecture Integration", () => {
730
+ let server: YNABMCPServer;
731
+
732
+ beforeEach(() => {
733
+ server = new YNABMCPServer(false);
734
+ });
735
+
736
+ it("should initialize all service modules during construction", () => {
737
+ // Verify the server has been constructed successfully with all modules
738
+ expect(server).toBeInstanceOf(YNABMCPServer);
739
+
740
+ // Check that core functionality from modules works through public interface
741
+ expect(server.getYNABAPI()).toBeDefined();
742
+ expect(server.getServer()).toBeDefined();
743
+ });
744
+
745
+ it("should use config module for environment validation", () => {
746
+ // The fact that constructor succeeds means config module is working
747
+ // This test verifies the integration is seamless
748
+ expect(server.getYNABAPI()).toBeDefined();
749
+ });
750
+
751
+ it("should handle resource requests through resource manager", async () => {
752
+ // Test that resources work (this goes through the resource manager now)
753
+ const mcpServer = server.getServer();
754
+ expect(mcpServer).toBeDefined();
755
+
756
+ // The server should be properly configured with resource handlers
757
+ // If the integration failed, the server wouldn't have the handlers
758
+ expect(() => server.getYNABAPI()).not.toThrow();
759
+ });
760
+
761
+ it("should handle prompt requests through prompt manager", async () => {
762
+ // Test that the server has prompt handling capability
763
+ // The integration ensures prompt handlers are properly set up
764
+ const mcpServer = server.getServer();
765
+ expect(mcpServer).toBeDefined();
766
+ });
767
+
768
+ it("should handle diagnostic requests through diagnostic manager", async () => {
769
+ // Test that diagnostic tools work through the tool registry integration
770
+ const registry = (server as unknown as { toolRegistry: ToolRegistry })
771
+ .toolRegistry;
772
+
773
+ // Verify diagnostic tool is registered
774
+ const tools = registry.listTools();
775
+ const diagnosticTool = tools.find(
776
+ (tool) => tool.name === "diagnostic_info",
777
+ );
778
+ expect(diagnosticTool).toBeDefined();
779
+ expect(diagnosticTool?.description).toContain("diagnostic information");
780
+ });
781
+
782
+ it("should maintain backward compatibility after modular refactoring", async () => {
783
+ // Test that all expected tools are still available
784
+ const registry = (server as unknown as { toolRegistry: ToolRegistry })
785
+ .toolRegistry;
786
+ const tools = registry.listTools();
787
+
788
+ // Use the shared expectedToolNames constant defined at the top of the test file
789
+
790
+ const actualToolNames = tools.map((tool) => tool.name).sort();
791
+ expect(actualToolNames).toEqual(expectedToolNames.sort());
792
+ });
793
+
794
+ it("should maintain same error handling behavior after refactoring", () => {
795
+ // Test that configuration errors are still properly thrown
796
+ const originalToken = process.env.YNAB_ACCESS_TOKEN;
797
+ process.env.YNAB_ACCESS_TOKEN = undefined;
798
+
799
+ try {
800
+ expect(() => new YNABMCPServer()).toThrow(/YNAB_ACCESS_TOKEN/i);
801
+ } finally {
802
+ // Restore token
803
+ process.env.YNAB_ACCESS_TOKEN = originalToken;
804
+ }
805
+ });
806
+
807
+ it("should delegate diagnostic collection to diagnostic manager", async () => {
808
+ const registry = (server as unknown as { toolRegistry: ToolRegistry })
809
+ .toolRegistry;
810
+ const accessToken = process.env.YNAB_ACCESS_TOKEN!;
811
+
812
+ // Test that diagnostic_info tool works and returns expected structure
813
+ const result = await registry.executeTool({
814
+ name: "diagnostic_info",
815
+ accessToken,
816
+ arguments: {
817
+ include_server: true,
818
+ include_memory: false,
819
+ include_environment: false,
820
+ include_security: false,
821
+ include_cache: false,
822
+ },
823
+ });
824
+
825
+ const diagnostics = parseCallToolJson(result);
826
+ expect(diagnostics.timestamp).toBeDefined();
827
+ expect(diagnostics.server).toBeDefined();
828
+ expect(diagnostics.server.name).toBe("ynab-mcp-server");
829
+ expect(diagnostics.server.version).toBeDefined();
830
+
831
+ // These should be undefined because we set include flags to false
832
+ expect(diagnostics.memory).toBeUndefined();
833
+ expect(diagnostics.environment).toBeUndefined();
834
+ expect(diagnostics.security).toBeUndefined();
835
+ expect(diagnostics.cache).toBeUndefined();
836
+ });
837
+ });
838
+
839
+ describe("ErrorHandler Integration", () => {
840
+ let server: YNABMCPServer;
841
+
842
+ beforeEach(() => {
843
+ server = new YNABMCPServer(false);
844
+ });
845
+
846
+ it("should create ErrorHandler instance with responseFormatter", () => {
847
+ // Verify that createErrorHandler was called with the formatter
848
+ expect(server).toBeInstanceOf(YNABMCPServer);
849
+
850
+ // The server should be successfully constructed with ErrorHandler injection
851
+ expect(server.getYNABAPI()).toBeDefined();
852
+ });
853
+
854
+ it("should create ErrorHandler with proper formatter", () => {
855
+ // Verify the server creates a working ErrorHandler by checking
856
+ // that the server's errorHandler instance produces valid output
857
+ const errorHandler = createErrorHandler({
858
+ format: (value: unknown) => JSON.stringify(value),
859
+ });
860
+ const result = errorHandler.createValidationError("Test error");
861
+
862
+ expect(result.content).toBeDefined();
863
+ expect(result.content[0].type).toBe("text");
864
+ expect(() => JSON.parse(result.content[0].text)).not.toThrow();
865
+ });
866
+
867
+ it("should use the same formatter for ErrorHandler and ToolRegistry", () => {
868
+ // Verify that the server uses dependency injection correctly
869
+ expect(server).toBeInstanceOf(YNABMCPServer);
870
+
871
+ // The fact that the server constructs successfully means dependency injection worked
872
+ // and both ErrorHandler and ToolRegistry are using the same formatter instance
873
+ });
874
+
875
+ it("should maintain existing error response format", async () => {
876
+ const registry = (server as unknown as { toolRegistry: ToolRegistry })
877
+ .toolRegistry;
878
+
879
+ // Test that error responses still have the expected structure
880
+ const result = await registry.executeTool({
881
+ name: "get_budget",
882
+ accessToken: process.env.YNAB_ACCESS_TOKEN!,
883
+ arguments: {} as Record<string, unknown>,
884
+ });
885
+
886
+ const payload = parseCallToolJson(result);
887
+ expect(payload.error).toBeDefined();
888
+ expect(payload.error.code).toBe("VALIDATION_ERROR");
889
+
890
+ // Verify the response is properly formatted JSON
891
+ expect(() => JSON.parse(result.content[0].text)).not.toThrow();
892
+ });
893
+
894
+ it("should produce consistent error responses across ErrorHandler instances with same formatter", () => {
895
+ const formatter = { format: (value: unknown) => JSON.stringify(value) };
896
+ const errorHandler1 = createErrorHandler(formatter);
897
+ const errorHandler2 = createErrorHandler(formatter);
898
+
899
+ const error = new ValidationError("Test error");
900
+ const result1 = errorHandler1.handleError(error, "testing");
901
+ const result2 = errorHandler2.handleError(error, "testing");
902
+
903
+ // Both should produce the same result structure
904
+ expect(result1.content[0].type).toBe(result2.content[0].type);
905
+ expect(() => JSON.parse(result1.content[0].text)).not.toThrow();
906
+ expect(() => JSON.parse(result2.content[0].text)).not.toThrow();
907
+ });
908
+ });
905
909
  });