@mastra/mongodb 0.11.1-alpha.0 → 0.11.1-alpha.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/mongodb",
3
- "version": "0.11.1-alpha.0",
3
+ "version": "0.11.1-alpha.1",
4
4
  "description": "MongoDB provider for Mastra - includes vector store capabilities",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -31,9 +31,9 @@
31
31
  "tsup": "^8.5.0",
32
32
  "typescript": "^5.8.3",
33
33
  "vitest": "^3.2.3",
34
- "@internal/lint": "0.0.13",
35
- "@mastra/core": "0.10.7-alpha.0",
36
- "@internal/storage-test-utils": "0.0.9"
34
+ "@internal/storage-test-utils": "0.0.9",
35
+ "@mastra/core": "0.10.7-alpha.1",
36
+ "@internal/lint": "0.0.13"
37
37
  },
38
38
  "peerDependencies": {
39
39
  "@mastra/core": ">=0.10.4-0 <0.11.0"
@@ -1,5 +1,6 @@
1
1
  import { MessageList } from '@mastra/core/agent';
2
2
  import type { MastraMessageContentV2 } from '@mastra/core/agent';
3
+ import { ErrorDomain, ErrorCategory, MastraError } from '@mastra/core/error';
3
4
  import type { MetricResult, TestInfo } from '@mastra/core/eval';
4
5
  import type { MastraMessageV1, MastraMessageV2, StorageThreadType } from '@mastra/core/memory';
5
6
  import type {
@@ -48,15 +49,27 @@ export class MongoDBStore extends MastraStorage {
48
49
  super({ name: 'MongoDBStore' });
49
50
  this.#isConnected = false;
50
51
 
51
- if (!config.url?.trim().length) {
52
- throw new Error(
53
- 'MongoDBStore: url must be provided and cannot be empty. Passing an empty string may cause fallback to local MongoDB defaults.',
54
- );
55
- }
52
+ try {
53
+ if (!config.url?.trim().length) {
54
+ throw new Error(
55
+ 'MongoDBStore: url must be provided and cannot be empty. Passing an empty string may cause fallback to local MongoDB defaults.',
56
+ );
57
+ }
56
58
 
57
- if (!config.dbName?.trim().length) {
58
- throw new Error(
59
- 'MongoDBStore: dbName must be provided and cannot be empty. Passing an empty string may cause fallback to local MongoDB defaults.',
59
+ if (!config.dbName?.trim().length) {
60
+ throw new Error(
61
+ 'MongoDBStore: dbName must be provided and cannot be empty. Passing an empty string may cause fallback to local MongoDB defaults.',
62
+ );
63
+ }
64
+ } catch (error) {
65
+ throw new MastraError(
66
+ {
67
+ id: 'STORAGE_MONGODB_STORE_CONSTRUCTOR_FAILED',
68
+ domain: ErrorDomain.STORAGE,
69
+ category: ErrorCategory.USER,
70
+ details: { url: config.url, dbName: config.dbName },
71
+ },
72
+ error,
60
73
  );
61
74
  }
62
75
 
@@ -104,7 +117,17 @@ export class MongoDBStore extends MastraStorage {
104
117
  await collection.deleteMany({});
105
118
  } catch (error) {
106
119
  if (error instanceof Error) {
107
- this.logger.error(error.message);
120
+ const matstraError = new MastraError(
121
+ {
122
+ id: 'STORAGE_MONGODB_STORE_CLEAR_TABLE_FAILED',
123
+ domain: ErrorDomain.STORAGE,
124
+ category: ErrorCategory.THIRD_PARTY,
125
+ details: { tableName },
126
+ },
127
+ error,
128
+ );
129
+ this.logger.error(matstraError.message);
130
+ this.logger?.trackException(matstraError);
108
131
  }
109
132
  }
110
133
  }
@@ -114,8 +137,19 @@ export class MongoDBStore extends MastraStorage {
114
137
  const collection = await this.getCollection(tableName);
115
138
  await collection.insertOne(record);
116
139
  } catch (error) {
117
- this.logger.error(`Error upserting into table ${tableName}: ${error}`);
118
- throw error;
140
+ if (error instanceof Error) {
141
+ const matstraError = new MastraError(
142
+ {
143
+ id: 'STORAGE_MONGODB_STORE_INSERT_FAILED',
144
+ domain: ErrorDomain.STORAGE,
145
+ category: ErrorCategory.THIRD_PARTY,
146
+ details: { tableName },
147
+ },
148
+ error,
149
+ );
150
+ this.logger.error(matstraError.message);
151
+ this.logger?.trackException(matstraError);
152
+ }
119
153
  }
120
154
  }
121
155
 
@@ -128,8 +162,15 @@ export class MongoDBStore extends MastraStorage {
128
162
  const collection = await this.getCollection(tableName);
129
163
  await collection.insertMany(records);
130
164
  } catch (error) {
131
- this.logger.error(`Error upserting into table ${tableName}: ${error}`);
132
- throw error;
165
+ throw new MastraError(
166
+ {
167
+ id: 'STORAGE_MONGODB_STORE_BATCH_INSERT_FAILED',
168
+ domain: ErrorDomain.STORAGE,
169
+ category: ErrorCategory.THIRD_PARTY,
170
+ details: { tableName },
171
+ },
172
+ error,
173
+ );
133
174
  }
134
175
  }
135
176
 
@@ -139,8 +180,15 @@ export class MongoDBStore extends MastraStorage {
139
180
  const collection = await this.getCollection(tableName);
140
181
  return (await collection.find(keys).toArray()) as R;
141
182
  } catch (error) {
142
- this.logger.error(`Error loading ${tableName} with keys ${JSON.stringify(keys)}: ${error}`);
143
- throw error;
183
+ throw new MastraError(
184
+ {
185
+ id: 'STORAGE_MONGODB_STORE_LOAD_FAILED',
186
+ domain: ErrorDomain.STORAGE,
187
+ category: ErrorCategory.THIRD_PARTY,
188
+ details: { tableName },
189
+ },
190
+ error,
191
+ );
144
192
  }
145
193
  }
146
194
 
@@ -157,8 +205,15 @@ export class MongoDBStore extends MastraStorage {
157
205
  metadata: typeof result.metadata === 'string' ? JSON.parse(result.metadata) : result.metadata,
158
206
  };
159
207
  } catch (error) {
160
- this.logger.error(`Error loading thread with ID ${threadId}: ${error}`);
161
- throw error;
208
+ throw new MastraError(
209
+ {
210
+ id: 'STORAGE_MONGODB_STORE_GET_THREAD_BY_ID_FAILED',
211
+ domain: ErrorDomain.STORAGE,
212
+ category: ErrorCategory.THIRD_PARTY,
213
+ details: { threadId },
214
+ },
215
+ error,
216
+ );
162
217
  }
163
218
  }
164
219
 
@@ -175,8 +230,15 @@ export class MongoDBStore extends MastraStorage {
175
230
  metadata: typeof result.metadata === 'string' ? JSON.parse(result.metadata) : result.metadata,
176
231
  }));
177
232
  } catch (error) {
178
- this.logger.error(`Error loading threads by resourceId ${resourceId}: ${error}`);
179
- throw error;
233
+ throw new MastraError(
234
+ {
235
+ id: 'STORAGE_MONGODB_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED',
236
+ domain: ErrorDomain.STORAGE,
237
+ category: ErrorCategory.THIRD_PARTY,
238
+ details: { resourceId },
239
+ },
240
+ error,
241
+ );
180
242
  }
181
243
  }
182
244
 
@@ -195,8 +257,15 @@ export class MongoDBStore extends MastraStorage {
195
257
  );
196
258
  return thread;
197
259
  } catch (error) {
198
- this.logger.error(`Error saving thread ${thread.id}: ${error}`);
199
- throw error;
260
+ throw new MastraError(
261
+ {
262
+ id: 'STORAGE_MONGODB_STORE_SAVE_THREAD_FAILED',
263
+ domain: ErrorDomain.STORAGE,
264
+ category: ErrorCategory.THIRD_PARTY,
265
+ details: { threadId: thread.id },
266
+ },
267
+ error,
268
+ );
200
269
  }
201
270
  }
202
271
 
@@ -211,7 +280,13 @@ export class MongoDBStore extends MastraStorage {
211
280
  }): Promise<StorageThreadType> {
212
281
  const thread = await this.getThreadById({ threadId: id });
213
282
  if (!thread) {
214
- throw new Error(`Thread ${id} not found`);
283
+ throw new MastraError({
284
+ id: 'STORAGE_MONGODB_STORE_UPDATE_THREAD_NOT_FOUND',
285
+ domain: ErrorDomain.STORAGE,
286
+ category: ErrorCategory.THIRD_PARTY,
287
+ details: { threadId: id },
288
+ text: `Thread ${id} not found`,
289
+ });
215
290
  }
216
291
 
217
292
  const updatedThread = {
@@ -235,8 +310,15 @@ export class MongoDBStore extends MastraStorage {
235
310
  },
236
311
  );
237
312
  } catch (error) {
238
- this.logger.error(`Error updating thread ${id}:) ${error}`);
239
- throw error;
313
+ throw new MastraError(
314
+ {
315
+ id: 'STORAGE_MONGODB_STORE_UPDATE_THREAD_FAILED',
316
+ domain: ErrorDomain.STORAGE,
317
+ category: ErrorCategory.THIRD_PARTY,
318
+ details: { threadId: id },
319
+ },
320
+ error,
321
+ );
240
322
  }
241
323
 
242
324
  return updatedThread;
@@ -251,8 +333,15 @@ export class MongoDBStore extends MastraStorage {
251
333
  const collectionThreads = await this.getCollection(TABLE_THREADS);
252
334
  await collectionThreads.deleteOne({ id: threadId });
253
335
  } catch (error) {
254
- this.logger.error(`Error deleting thread ${threadId}: ${error}`);
255
- throw error;
336
+ throw new MastraError(
337
+ {
338
+ id: 'STORAGE_MONGODB_STORE_DELETE_THREAD_FAILED',
339
+ domain: ErrorDomain.STORAGE,
340
+ category: ErrorCategory.THIRD_PARTY,
341
+ details: { threadId },
342
+ },
343
+ error,
344
+ );
256
345
  }
257
346
  }
258
347
 
@@ -266,7 +355,7 @@ export class MongoDBStore extends MastraStorage {
266
355
  format?: 'v1' | 'v2';
267
356
  }): Promise<MastraMessageV1[] | MastraMessageV2[]> {
268
357
  try {
269
- const limit = typeof selectBy?.last === 'number' ? selectBy.last : 40;
358
+ const limit = this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
270
359
  const include = selectBy?.include || [];
271
360
  let messages: MastraMessageV2[] = [];
272
361
  let allMessages: MastraMessageV2[] = [];
@@ -323,8 +412,15 @@ export class MongoDBStore extends MastraStorage {
323
412
  if (format === `v2`) return list.get.all.v2();
324
413
  return list.get.all.v1();
325
414
  } catch (error) {
326
- this.logger.error('Error getting messages:', error as Error);
327
- throw error;
415
+ throw new MastraError(
416
+ {
417
+ id: 'STORAGE_MONGODB_STORE_GET_MESSAGES_FAILED',
418
+ domain: ErrorDomain.STORAGE,
419
+ category: ErrorCategory.THIRD_PARTY,
420
+ details: { threadId },
421
+ },
422
+ error,
423
+ );
328
424
  }
329
425
  }
330
426
 
@@ -423,31 +519,42 @@ export class MongoDBStore extends MastraStorage {
423
519
  });
424
520
  }
425
521
 
426
- const collection = await this.getCollection(TABLE_TRACES);
427
- const result = await collection
428
- .find(query, {
429
- sort: { startTime: -1 },
430
- })
431
- .limit(limit)
432
- .skip(offset)
433
- .toArray();
434
-
435
- return result.map(row => ({
436
- id: row.id,
437
- parentSpanId: row.parentSpanId,
438
- traceId: row.traceId,
439
- name: row.name,
440
- scope: row.scope,
441
- kind: row.kind,
442
- status: safelyParseJSON(row.status as string),
443
- events: safelyParseJSON(row.events as string),
444
- links: safelyParseJSON(row.links as string),
445
- attributes: safelyParseJSON(row.attributes as string),
446
- startTime: row.startTime,
447
- endTime: row.endTime,
448
- other: safelyParseJSON(row.other as string),
449
- createdAt: row.createdAt,
450
- })) as any;
522
+ try {
523
+ const collection = await this.getCollection(TABLE_TRACES);
524
+ const result = await collection
525
+ .find(query, {
526
+ sort: { startTime: -1 },
527
+ })
528
+ .limit(limit)
529
+ .skip(offset)
530
+ .toArray();
531
+
532
+ return result.map(row => ({
533
+ id: row.id,
534
+ parentSpanId: row.parentSpanId,
535
+ traceId: row.traceId,
536
+ name: row.name,
537
+ scope: row.scope,
538
+ kind: row.kind,
539
+ status: safelyParseJSON(row.status as string),
540
+ events: safelyParseJSON(row.events as string),
541
+ links: safelyParseJSON(row.links as string),
542
+ attributes: safelyParseJSON(row.attributes as string),
543
+ startTime: row.startTime,
544
+ endTime: row.endTime,
545
+ other: safelyParseJSON(row.other as string),
546
+ createdAt: row.createdAt,
547
+ })) as any;
548
+ } catch (error) {
549
+ throw new MastraError(
550
+ {
551
+ id: 'STORAGE_MONGODB_STORE_GET_TRACES_FAILED',
552
+ domain: ErrorDomain.STORAGE,
553
+ category: ErrorCategory.THIRD_PARTY,
554
+ },
555
+ error,
556
+ );
557
+ }
451
558
  }
452
559
 
453
560
  async getWorkflowRuns({
@@ -487,46 +594,57 @@ export class MongoDBStore extends MastraStorage {
487
594
  }
488
595
  }
489
596
 
490
- const collection = await this.getCollection(TABLE_WORKFLOW_SNAPSHOT);
491
- let total = 0;
492
- // Only get total count when using pagination
493
- if (limit !== undefined && offset !== undefined) {
494
- total = await collection.countDocuments(query);
495
- }
597
+ try {
598
+ const collection = await this.getCollection(TABLE_WORKFLOW_SNAPSHOT);
599
+ let total = 0;
600
+ // Only get total count when using pagination
601
+ if (limit !== undefined && offset !== undefined) {
602
+ total = await collection.countDocuments(query);
603
+ }
496
604
 
497
- // Get results
498
- const request = collection.find(query).sort({ createdAt: 'desc' });
499
- if (limit) {
500
- request.limit(limit);
501
- }
605
+ // Get results
606
+ const request = collection.find(query).sort({ createdAt: 'desc' });
607
+ if (limit) {
608
+ request.limit(limit);
609
+ }
502
610
 
503
- if (offset) {
504
- request.skip(offset);
505
- }
611
+ if (offset) {
612
+ request.skip(offset);
613
+ }
506
614
 
507
- const result = await request.toArray();
508
- const runs = result.map(row => {
509
- let parsedSnapshot: WorkflowRunState | string = row.snapshot;
510
- if (typeof parsedSnapshot === 'string') {
511
- try {
512
- parsedSnapshot = JSON.parse(row.snapshot as string) as WorkflowRunState;
513
- } catch (e) {
514
- // If parsing fails, return the raw snapshot string
515
- console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
615
+ const result = await request.toArray();
616
+ const runs = result.map(row => {
617
+ let parsedSnapshot: WorkflowRunState | string = row.snapshot;
618
+ if (typeof parsedSnapshot === 'string') {
619
+ try {
620
+ parsedSnapshot = JSON.parse(row.snapshot as string) as WorkflowRunState;
621
+ } catch (e) {
622
+ // If parsing fails, return the raw snapshot string
623
+ console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
624
+ }
516
625
  }
517
- }
518
626
 
519
- return {
520
- workflowName: row.workflow_name as string,
521
- runId: row.run_id as string,
522
- snapshot: parsedSnapshot,
523
- createdAt: new Date(row.createdAt as string),
524
- updatedAt: new Date(row.updatedAt as string),
525
- };
526
- });
627
+ return {
628
+ workflowName: row.workflow_name as string,
629
+ runId: row.run_id as string,
630
+ snapshot: parsedSnapshot,
631
+ createdAt: new Date(row.createdAt as string),
632
+ updatedAt: new Date(row.updatedAt as string),
633
+ };
634
+ });
527
635
 
528
- // Use runs.length as total when not paginating
529
- return { runs, total: total || runs.length };
636
+ // Use runs.length as total when not paginating
637
+ return { runs, total: total || runs.length };
638
+ } catch (error) {
639
+ throw new MastraError(
640
+ {
641
+ id: 'STORAGE_MONGODB_STORE_GET_WORKFLOW_RUNS_FAILED',
642
+ domain: ErrorDomain.STORAGE,
643
+ category: ErrorCategory.THIRD_PARTY,
644
+ },
645
+ error,
646
+ );
647
+ }
530
648
  }
531
649
 
532
650
  async getEvalsByAgentName(agentName: string, type?: 'test' | 'live'): Promise<EvalRow[]> {
@@ -565,8 +683,15 @@ export class MongoDBStore extends MastraStorage {
565
683
  if (error instanceof Error && error.message.includes('no such table')) {
566
684
  return [];
567
685
  }
568
- this.logger.error('Failed to get evals for the specified agent: ' + (error as any)?.message);
569
- throw error;
686
+ throw new MastraError(
687
+ {
688
+ id: 'STORAGE_MONGODB_STORE_GET_EVALS_BY_AGENT_NAME_FAILED',
689
+ domain: ErrorDomain.STORAGE,
690
+ category: ErrorCategory.THIRD_PARTY,
691
+ details: { agentName },
692
+ },
693
+ error,
694
+ );
570
695
  }
571
696
  }
572
697
 
@@ -596,8 +721,15 @@ export class MongoDBStore extends MastraStorage {
596
721
  { upsert: true },
597
722
  );
598
723
  } catch (error) {
599
- this.logger.error(`Error persisting workflow snapshot: ${error}`);
600
- throw error;
724
+ throw new MastraError(
725
+ {
726
+ id: 'STORAGE_MONGODB_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED',
727
+ domain: ErrorDomain.STORAGE,
728
+ category: ErrorCategory.THIRD_PARTY,
729
+ details: { workflowName, runId },
730
+ },
731
+ error,
732
+ );
601
733
  }
602
734
  }
603
735
 
@@ -623,8 +755,15 @@ export class MongoDBStore extends MastraStorage {
623
755
 
624
756
  return JSON.parse(result[0].snapshot);
625
757
  } catch (error) {
626
- console.error('Error loading workflow snapshot:', error);
627
- throw error;
758
+ throw new MastraError(
759
+ {
760
+ id: 'STORAGE_MONGODB_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED',
761
+ domain: ErrorDomain.STORAGE,
762
+ category: ErrorCategory.THIRD_PARTY,
763
+ details: { workflowName, runId },
764
+ },
765
+ error,
766
+ );
628
767
  }
629
768
  }
630
769
 
@@ -653,8 +792,15 @@ export class MongoDBStore extends MastraStorage {
653
792
 
654
793
  return this.parseWorkflowRun(result);
655
794
  } catch (error) {
656
- console.error('Error getting workflow run by ID:', error);
657
- throw error;
795
+ throw new MastraError(
796
+ {
797
+ id: 'STORAGE_MONGODB_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED',
798
+ domain: ErrorDomain.STORAGE,
799
+ category: ErrorCategory.THIRD_PARTY,
800
+ details: { runId },
801
+ },
802
+ error,
803
+ );
658
804
  }
659
805
  }
660
806
 
@@ -722,7 +868,12 @@ export class MongoDBStore extends MastraStorage {
722
868
  }
723
869
 
724
870
  async getTracesPaginated(_args: StorageGetTracesArg): Promise<PaginationInfo & { traces: Trace[] }> {
725
- throw new Error('Method not implemented.');
871
+ throw new MastraError({
872
+ id: 'STORAGE_MONGODB_STORE_GET_TRACES_PAGINATED_FAILED',
873
+ domain: ErrorDomain.STORAGE,
874
+ category: ErrorCategory.THIRD_PARTY,
875
+ text: 'Method not implemented.',
876
+ });
726
877
  }
727
878
 
728
879
  async getThreadsByResourceIdPaginated(_args: {
@@ -730,17 +881,38 @@ export class MongoDBStore extends MastraStorage {
730
881
  page?: number;
731
882
  perPage?: number;
732
883
  }): Promise<PaginationInfo & { threads: StorageThreadType[] }> {
733
- throw new Error('Method not implemented.');
884
+ throw new MastraError({
885
+ id: 'STORAGE_MONGODB_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED',
886
+ domain: ErrorDomain.STORAGE,
887
+ category: ErrorCategory.THIRD_PARTY,
888
+ text: 'Method not implemented.',
889
+ });
734
890
  }
735
891
 
736
892
  async getMessagesPaginated(
737
893
  _args: StorageGetMessagesArg,
738
894
  ): Promise<PaginationInfo & { messages: MastraMessageV1[] | MastraMessageV2[] }> {
739
- throw new Error('Method not implemented.');
895
+ throw new MastraError({
896
+ id: 'STORAGE_MONGODB_STORE_GET_MESSAGES_PAGINATED_FAILED',
897
+ domain: ErrorDomain.STORAGE,
898
+ category: ErrorCategory.THIRD_PARTY,
899
+ text: 'Method not implemented.',
900
+ });
740
901
  }
741
902
 
742
903
  async close(): Promise<void> {
743
- await this.#client.close();
904
+ try {
905
+ await this.#client.close();
906
+ } catch (error) {
907
+ throw new MastraError(
908
+ {
909
+ id: 'STORAGE_MONGODB_STORE_CLOSE_FAILED',
910
+ domain: ErrorDomain.STORAGE,
911
+ category: ErrorCategory.USER,
912
+ },
913
+ error,
914
+ );
915
+ }
744
916
  }
745
917
 
746
918
  async updateMessages(_args: {