@dizzlkheinz/ynab-mcpb 0.18.3 → 0.18.4

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 (33) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/bundle/index.cjs +40 -40
  3. package/dist/tools/reconcileAdapter.js +3 -0
  4. package/dist/tools/reconciliation/analyzer.js +72 -7
  5. package/dist/tools/reconciliation/reportFormatter.js +26 -2
  6. package/dist/tools/reconciliation/types.d.ts +3 -0
  7. package/dist/tools/transactionSchemas.d.ts +309 -0
  8. package/dist/tools/transactionSchemas.js +215 -0
  9. package/dist/tools/transactionTools.d.ts +3 -281
  10. package/dist/tools/transactionTools.js +4 -559
  11. package/dist/tools/transactionUtils.d.ts +31 -0
  12. package/dist/tools/transactionUtils.js +349 -0
  13. package/docs/plans/2025-12-25-transaction-tools-refactor-design.md +211 -0
  14. package/docs/plans/2025-12-25-transaction-tools-refactor.md +905 -0
  15. package/package.json +4 -2
  16. package/scripts/run-all-tests.js +196 -0
  17. package/src/tools/__tests__/transactionSchemas.test.ts +1188 -0
  18. package/src/tools/__tests__/transactionUtils.test.ts +989 -0
  19. package/src/tools/reconcileAdapter.ts +6 -0
  20. package/src/tools/reconciliation/__tests__/adapter.causes.test.ts +22 -8
  21. package/src/tools/reconciliation/__tests__/adapter.test.ts +3 -0
  22. package/src/tools/reconciliation/__tests__/analyzer.test.ts +65 -0
  23. package/src/tools/reconciliation/__tests__/recommendationEngine.test.ts +3 -0
  24. package/src/tools/reconciliation/__tests__/reportFormatter.test.ts +4 -1
  25. package/src/tools/reconciliation/__tests__/scenarios/adapterCurrency.scenario.test.ts +3 -0
  26. package/src/tools/reconciliation/__tests__/scenarios/extremes.scenario.test.ts +5 -1
  27. package/src/tools/reconciliation/__tests__/schemaUrl.test.ts +22 -8
  28. package/src/tools/reconciliation/analyzer.ts +127 -11
  29. package/src/tools/reconciliation/reportFormatter.ts +39 -2
  30. package/src/tools/reconciliation/types.ts +6 -0
  31. package/src/tools/transactionSchemas.ts +453 -0
  32. package/src/tools/transactionTools.ts +102 -823
  33. package/src/tools/transactionUtils.ts +536 -0
@@ -0,0 +1,536 @@
1
+ import { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
2
+ import { createHash } from 'crypto';
3
+ import * as ynab from 'ynab';
4
+ import type { SaveTransactionsResponseData } from 'ynab/dist/models/SaveTransactionsResponseData.js';
5
+ import { ValidationError } from '../types/index.js';
6
+ import { responseFormatter } from '../server/responseFormatter.js';
7
+ import { cacheManager, CacheManager } from '../server/cacheManager.js';
8
+ import type { DeltaCache } from '../server/deltaCache.js';
9
+ import type { ServerKnowledgeStore } from '../server/serverKnowledgeStore.js';
10
+ import type {
11
+ CategorySource,
12
+ TransactionCacheInvalidationOptions,
13
+ CorrelationPayload,
14
+ CorrelationPayloadInput,
15
+ BulkTransactionInput,
16
+ BulkTransactionResult,
17
+ BulkCreateResponse,
18
+ BulkUpdateResponse,
19
+ } from './transactionSchemas.js';
20
+ import { globalRequestLogger } from '../server/requestLogger.js';
21
+
22
+ /**
23
+ * Transaction Utilities
24
+ *
25
+ * This module contains utility functions for transaction operations.
26
+ * Extracted from transactionTools.ts for better code organization.
27
+ */
28
+
29
+ // ============================================================================
30
+ // Response Size Constants
31
+ // ============================================================================
32
+
33
+ const FULL_RESPONSE_THRESHOLD = 64 * 1024;
34
+ const SUMMARY_RESPONSE_THRESHOLD = 96 * 1024;
35
+ const MAX_RESPONSE_BYTES = 100 * 1024;
36
+
37
+ // ============================================================================
38
+ // Transaction Helpers
39
+ // ============================================================================
40
+
41
+ /**
42
+ * Utility function to ensure transaction is not null/undefined
43
+ */
44
+ export function ensureTransaction<T>(transaction: T | undefined, errorMessage: string): T {
45
+ if (!transaction) {
46
+ throw new Error(errorMessage);
47
+ }
48
+ return transaction;
49
+ }
50
+
51
+ // ============================================================================
52
+ // Category Helpers
53
+ // ============================================================================
54
+
55
+ /**
56
+ * Appends category IDs from a source to a target set
57
+ */
58
+ export function appendCategoryIds(source: CategorySource | undefined, target: Set<string>): void {
59
+ if (!source) {
60
+ return;
61
+ }
62
+ if (source.category_id) {
63
+ target.add(source.category_id);
64
+ }
65
+ if (Array.isArray(source.subtransactions)) {
66
+ for (const sub of source.subtransactions) {
67
+ if (sub?.category_id) {
68
+ target.add(sub.category_id);
69
+ }
70
+ }
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Collects category IDs from multiple sources
76
+ */
77
+ export function collectCategoryIdsFromSources(
78
+ ...sources: (CategorySource | undefined)[]
79
+ ): Set<string> {
80
+ const result = new Set<string>();
81
+ for (const source of sources) {
82
+ appendCategoryIds(source, result);
83
+ }
84
+ return result;
85
+ }
86
+
87
+ /**
88
+ * Checks if two sets are equal
89
+ */
90
+ export function setsEqual<T>(a: Set<T>, b: Set<T>): boolean {
91
+ if (a.size !== b.size) {
92
+ return false;
93
+ }
94
+ for (const value of a) {
95
+ if (!b.has(value)) {
96
+ return false;
97
+ }
98
+ }
99
+ return true;
100
+ }
101
+
102
+ // ============================================================================
103
+ // Cache Invalidation
104
+ // ============================================================================
105
+
106
+ /**
107
+ * Converts a date string to a month key
108
+ */
109
+ export const toMonthKey = (date: string): string => `${date.slice(0, 7)}-01`;
110
+
111
+ /**
112
+ * Invalidates transaction-related caches after write operations
113
+ */
114
+ export function invalidateTransactionCaches(
115
+ deltaCache: DeltaCache,
116
+ knowledgeStore: ServerKnowledgeStore,
117
+ budgetId: string,
118
+ serverKnowledge: number | undefined,
119
+ affectedAccountIds: Set<string>,
120
+ affectedMonths: Set<string>,
121
+ options: TransactionCacheInvalidationOptions = {},
122
+ ): void {
123
+ deltaCache.invalidate(budgetId, 'transactions');
124
+ cacheManager.delete(CacheManager.generateKey('transactions', 'list', budgetId));
125
+
126
+ for (const accountId of affectedAccountIds) {
127
+ const accountPrefix = CacheManager.generateKey('transactions', 'account', budgetId, accountId);
128
+ cacheManager.deleteByPrefix(accountPrefix);
129
+ }
130
+
131
+ const invalidateAccountsList = options.accountTotalsChanged ?? true;
132
+ if (invalidateAccountsList) {
133
+ cacheManager.delete(CacheManager.generateKey('accounts', 'list', budgetId));
134
+ }
135
+ for (const accountId of affectedAccountIds) {
136
+ cacheManager.delete(CacheManager.generateKey('account', 'get', budgetId, accountId));
137
+ }
138
+
139
+ const affectedCategoryIds = options.affectedCategoryIds ?? new Set<string>();
140
+ const shouldInvalidateCategories =
141
+ options.invalidateAllCategories || affectedCategoryIds.size > 0;
142
+ if (shouldInvalidateCategories) {
143
+ cacheManager.delete(CacheManager.generateKey('categories', 'list', budgetId));
144
+ for (const categoryId of affectedCategoryIds) {
145
+ cacheManager.delete(CacheManager.generateKey('category', 'get', budgetId, categoryId));
146
+ }
147
+ }
148
+
149
+ const shouldInvalidateMonths = options.invalidateMonths ?? affectedMonths.size > 0;
150
+ if (shouldInvalidateMonths) {
151
+ cacheManager.delete(CacheManager.generateKey('months', 'list', budgetId));
152
+ deltaCache.invalidate(budgetId, 'months');
153
+ for (const month of affectedMonths) {
154
+ cacheManager.delete(CacheManager.generateKey('month', 'get', budgetId, month));
155
+ }
156
+ }
157
+
158
+ if (serverKnowledge !== undefined) {
159
+ const transactionCacheKey = CacheManager.generateKey('transactions', 'list', budgetId);
160
+ knowledgeStore.update(transactionCacheKey, serverKnowledge);
161
+ if (invalidateAccountsList) {
162
+ const accountsCacheKey = CacheManager.generateKey('accounts', 'list', budgetId);
163
+ knowledgeStore.update(accountsCacheKey, serverKnowledge);
164
+ }
165
+ if (shouldInvalidateMonths && affectedMonths.size > 0) {
166
+ const monthsCacheKey = CacheManager.generateKey('months', 'list', budgetId);
167
+ knowledgeStore.update(monthsCacheKey, serverKnowledge);
168
+ }
169
+ }
170
+ }
171
+
172
+ // ============================================================================
173
+ // Correlation Utilities
174
+ // ============================================================================
175
+
176
+ /**
177
+ * Generates a correlation key for a transaction
178
+ */
179
+ export function generateCorrelationKey(transaction: {
180
+ account_id?: string;
181
+ date?: string;
182
+ amount?: number;
183
+ payee_id?: string | null;
184
+ payee_name?: string | null;
185
+ category_id?: string | null;
186
+ memo?: string | null;
187
+ cleared?: ynab.TransactionClearedStatus;
188
+ approved?: boolean;
189
+ flag_color?: ynab.TransactionFlagColor | null;
190
+ import_id?: string | null;
191
+ }): string {
192
+ if (transaction.import_id) {
193
+ return transaction.import_id;
194
+ }
195
+
196
+ const segments = [
197
+ `account:${transaction.account_id ?? ''}`,
198
+ `date:${transaction.date ?? ''}`,
199
+ `amount:${transaction.amount ?? 0}`,
200
+ `payee:${transaction.payee_id ?? transaction.payee_name ?? ''}`,
201
+ `category:${transaction.category_id ?? ''}`,
202
+ `memo:${transaction.memo ?? ''}`,
203
+ `cleared:${transaction.cleared ?? ''}`,
204
+ `approved:${transaction.approved ?? false}`,
205
+ `flag:${transaction.flag_color ?? ''}`,
206
+ ];
207
+
208
+ const normalized = segments.join('|');
209
+ const hash = createHash('sha256').update(normalized).digest('hex').slice(0, 16);
210
+ return `hash:${hash}`;
211
+ }
212
+
213
+ /**
214
+ * Converts a transaction input to a correlation payload
215
+ */
216
+ export function toCorrelationPayload(transaction: CorrelationPayloadInput): CorrelationPayload {
217
+ const payload: CorrelationPayload = {};
218
+ if (transaction.account_id !== undefined) {
219
+ payload.account_id = transaction.account_id;
220
+ }
221
+ if (transaction.date !== undefined) {
222
+ payload.date = transaction.date;
223
+ }
224
+ if (transaction.amount !== undefined) {
225
+ payload.amount = transaction.amount;
226
+ }
227
+ if (transaction.cleared !== undefined) {
228
+ payload.cleared = transaction.cleared;
229
+ }
230
+ if (transaction.approved !== undefined) {
231
+ payload.approved = transaction.approved;
232
+ }
233
+ if (transaction.flag_color !== undefined) {
234
+ payload.flag_color = transaction.flag_color;
235
+ }
236
+ payload.payee_id = transaction.payee_id ?? null;
237
+ payload.payee_name = transaction.payee_name ?? null;
238
+ payload.category_id = transaction.category_id ?? null;
239
+ payload.memo = transaction.memo ?? null;
240
+ payload.import_id = transaction.import_id ?? null;
241
+ return payload;
242
+ }
243
+
244
+ /**
245
+ * Correlates bulk transaction requests with YNAB response data
246
+ */
247
+ export function correlateResults(
248
+ requests: BulkTransactionInput[],
249
+ responseData: SaveTransactionsResponseData,
250
+ duplicateImportIds: Set<string>,
251
+ ): BulkTransactionResult[] {
252
+ const createdByImportId = new Map<string, string[]>();
253
+ const createdByHash = new Map<string, string[]>();
254
+ const responseTransactions = responseData.transactions ?? [];
255
+
256
+ const register = (map: Map<string, string[]>, key: string, transactionId: string): void => {
257
+ const existing = map.get(key);
258
+ if (existing) {
259
+ existing.push(transactionId);
260
+ return;
261
+ }
262
+ map.set(key, [transactionId]);
263
+ };
264
+
265
+ for (const transaction of responseTransactions) {
266
+ if (!transaction.id) {
267
+ continue;
268
+ }
269
+ const key = generateCorrelationKey(transaction);
270
+ if (key.startsWith('hash:')) {
271
+ register(createdByHash, key, transaction.id);
272
+ } else {
273
+ register(createdByImportId, key, transaction.id);
274
+ }
275
+ }
276
+
277
+ const popId = (map: Map<string, string[]>, key: string): string | undefined => {
278
+ const bucket = map.get(key);
279
+ if (!bucket || bucket.length === 0) {
280
+ return undefined;
281
+ }
282
+ const [transactionId] = bucket.splice(0, 1);
283
+ if (bucket.length === 0) {
284
+ map.delete(key);
285
+ }
286
+ return transactionId;
287
+ };
288
+
289
+ const correlatedResults: BulkTransactionResult[] = [];
290
+
291
+ for (const [index, transaction] of requests.entries()) {
292
+ const normalizedRequest = toCorrelationPayload(transaction);
293
+ const correlationKey = generateCorrelationKey(normalizedRequest);
294
+
295
+ if (transaction.import_id && duplicateImportIds.has(transaction.import_id)) {
296
+ correlatedResults.push({
297
+ request_index: index,
298
+ status: 'duplicate',
299
+ correlation_key: correlationKey,
300
+ });
301
+ continue;
302
+ }
303
+
304
+ let transactionId: string | undefined;
305
+ if (correlationKey.startsWith('hash:')) {
306
+ transactionId = popId(createdByHash, correlationKey);
307
+ } else {
308
+ transactionId = popId(createdByImportId, correlationKey);
309
+ }
310
+
311
+ if (!transactionId && !correlationKey.startsWith('hash:')) {
312
+ // Attempt hash-based fallback if import_id was not matched.
313
+ const hashKey = generateCorrelationKey(
314
+ toCorrelationPayload({ ...transaction, import_id: undefined }),
315
+ );
316
+ transactionId = popId(createdByHash, hashKey);
317
+ }
318
+
319
+ if (transactionId) {
320
+ const successResult: BulkTransactionResult = {
321
+ request_index: index,
322
+ status: 'created',
323
+ correlation_key: correlationKey,
324
+ };
325
+ successResult.transaction_id = transactionId;
326
+ correlatedResults.push(successResult);
327
+ continue;
328
+ }
329
+
330
+ globalRequestLogger.logError(
331
+ 'ynab:create_transactions',
332
+ 'correlate_results',
333
+ {
334
+ request_index: index,
335
+ correlation_key: correlationKey,
336
+ request: {
337
+ account_id: transaction.account_id,
338
+ date: transaction.date,
339
+ amount: transaction.amount,
340
+ import_id: transaction.import_id,
341
+ },
342
+ },
343
+ 'correlation_failed',
344
+ );
345
+
346
+ correlatedResults.push({
347
+ request_index: index,
348
+ status: 'failed',
349
+ correlation_key: correlationKey,
350
+ error_code: 'correlation_failed',
351
+ error: 'Unable to correlate request transaction with YNAB response',
352
+ });
353
+ }
354
+
355
+ return correlatedResults;
356
+ }
357
+
358
+ // ============================================================================
359
+ // Response Utilities
360
+ // ============================================================================
361
+
362
+ /**
363
+ * Estimates the size of a payload in bytes
364
+ */
365
+ export function estimatePayloadSize(payload: BulkCreateResponse | BulkUpdateResponse): number {
366
+ return Buffer.byteLength(JSON.stringify(payload), 'utf8');
367
+ }
368
+
369
+ /**
370
+ * Finalizes bulk create response based on size constraints
371
+ */
372
+ export function finalizeResponse(response: BulkCreateResponse): BulkCreateResponse {
373
+ const appendMessage = (message: string | undefined, addition: string): string => {
374
+ if (!message) {
375
+ return addition;
376
+ }
377
+ if (message.includes(addition)) {
378
+ return message;
379
+ }
380
+ return `${message} ${addition}`;
381
+ };
382
+
383
+ const fullSize = estimatePayloadSize({ ...response, mode: 'full' });
384
+ if (fullSize <= FULL_RESPONSE_THRESHOLD) {
385
+ return { ...response, mode: 'full' };
386
+ }
387
+
388
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
389
+ const { transactions, ...summaryResponse } = response;
390
+ const summaryPayload: BulkCreateResponse = {
391
+ ...summaryResponse,
392
+ message: appendMessage(
393
+ response.message,
394
+ 'Response downgraded to summary to stay under size limits.',
395
+ ),
396
+ mode: 'summary',
397
+ };
398
+
399
+ if (estimatePayloadSize(summaryPayload) <= SUMMARY_RESPONSE_THRESHOLD) {
400
+ return summaryPayload;
401
+ }
402
+
403
+ const idsOnlyPayload: BulkCreateResponse = {
404
+ ...summaryPayload,
405
+ results: summaryResponse.results.map((result) => ({
406
+ request_index: result.request_index,
407
+ status: result.status,
408
+ transaction_id: result.transaction_id,
409
+ correlation_key: result.correlation_key,
410
+ error: result.error,
411
+ })),
412
+ message: appendMessage(
413
+ summaryResponse.message,
414
+ 'Response downgraded to ids_only to meet 100KB limit.',
415
+ ),
416
+ mode: 'ids_only',
417
+ };
418
+
419
+ if (estimatePayloadSize(idsOnlyPayload) <= MAX_RESPONSE_BYTES) {
420
+ return idsOnlyPayload;
421
+ }
422
+
423
+ throw new ValidationError(
424
+ 'RESPONSE_TOO_LARGE: Unable to format bulk create response within 100KB limit',
425
+ `Batch size: ${response.summary.total_requested} transactions`,
426
+ ['Reduce the batch size and retry', 'Consider splitting into multiple smaller batches'],
427
+ );
428
+ }
429
+
430
+ /**
431
+ * Finalizes bulk update response based on size constraints
432
+ */
433
+ export function finalizeBulkUpdateResponse(response: BulkUpdateResponse): BulkUpdateResponse {
434
+ const appendMessage = (message: string | undefined, addition: string): string => {
435
+ if (!message) {
436
+ return addition;
437
+ }
438
+ if (message.includes(addition)) {
439
+ return message;
440
+ }
441
+ return `${message} ${addition}`;
442
+ };
443
+
444
+ const fullSize = estimatePayloadSize(response);
445
+ if (fullSize <= FULL_RESPONSE_THRESHOLD) {
446
+ return { ...response, mode: 'full' };
447
+ }
448
+
449
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
450
+ const { transactions, ...summaryResponse } = response;
451
+ const summaryPayload: BulkUpdateResponse = {
452
+ ...summaryResponse,
453
+ message: appendMessage(
454
+ response.message,
455
+ 'Response downgraded to summary to stay under size limits.',
456
+ ),
457
+ mode: 'summary',
458
+ };
459
+
460
+ if (estimatePayloadSize(summaryPayload) <= SUMMARY_RESPONSE_THRESHOLD) {
461
+ return summaryPayload;
462
+ }
463
+
464
+ const idsOnlyPayload: BulkUpdateResponse = {
465
+ ...summaryPayload,
466
+ results: summaryResponse.results.map((result) => {
467
+ const simplified: BulkUpdateResponse['results'][number] = {
468
+ request_index: result.request_index,
469
+ status: result.status,
470
+ transaction_id: result.transaction_id,
471
+ correlation_key: result.correlation_key,
472
+ };
473
+ if (result.error) {
474
+ simplified.error = result.error;
475
+ }
476
+ if (result.error_code) {
477
+ simplified.error_code = result.error_code;
478
+ }
479
+ return simplified;
480
+ }),
481
+ message: appendMessage(
482
+ summaryResponse.message,
483
+ 'Response downgraded to ids_only to meet 100KB limit.',
484
+ ),
485
+ mode: 'ids_only',
486
+ };
487
+
488
+ if (estimatePayloadSize(idsOnlyPayload) <= MAX_RESPONSE_BYTES) {
489
+ return idsOnlyPayload;
490
+ }
491
+
492
+ throw new ValidationError(
493
+ 'RESPONSE_TOO_LARGE: Unable to format bulk update response within 100KB limit',
494
+ `Batch size: ${response.summary.total_requested} transactions`,
495
+ ['Reduce the batch size and retry', 'Consider splitting into multiple smaller batches'],
496
+ );
497
+ }
498
+
499
+ // ============================================================================
500
+ // Error Handling
501
+ // ============================================================================
502
+
503
+ /**
504
+ * Handles errors from transaction-related API calls
505
+ */
506
+ export function handleTransactionError(error: unknown, defaultMessage: string): CallToolResult {
507
+ let errorMessage = defaultMessage;
508
+
509
+ if (error instanceof Error) {
510
+ if (error.message.includes('401') || error.message.includes('Unauthorized')) {
511
+ errorMessage = 'Invalid or expired YNAB access token';
512
+ } else if (error.message.includes('403') || error.message.includes('Forbidden')) {
513
+ errorMessage = 'Insufficient permissions to access YNAB data';
514
+ } else if (error.message.includes('404') || error.message.includes('Not Found')) {
515
+ errorMessage = 'Budget, account, category, or transaction not found';
516
+ } else if (error.message.includes('429') || error.message.includes('Too Many Requests')) {
517
+ errorMessage = 'Rate limit exceeded. Please try again later';
518
+ } else if (error.message.includes('500') || error.message.includes('Internal Server Error')) {
519
+ errorMessage = 'YNAB service is currently unavailable';
520
+ }
521
+ }
522
+
523
+ return {
524
+ isError: true,
525
+ content: [
526
+ {
527
+ type: 'text',
528
+ text: responseFormatter.format({
529
+ error: {
530
+ message: errorMessage,
531
+ },
532
+ }),
533
+ },
534
+ ],
535
+ };
536
+ }