@mastra/mongodb 1.4.0 → 1.5.0-alpha.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.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { createVectorErrorId, AgentsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, createStorageErrorId, normalizePerPage, calculatePagination, BlobStore, TABLE_SKILL_BLOBS, MCPClientsStorage, TABLE_MCP_CLIENTS, TABLE_MCP_CLIENT_VERSIONS, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, safelyParseJSON, ObservabilityStorage, TABLE_SPANS, listTracesArgsSchema, toTraceSpans, PromptBlocksStorage, TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS, ScorerDefinitionsStorage, TABLE_SCORER_DEFINITIONS, TABLE_SCORER_DEFINITION_VERSIONS, ScoresStorage, TABLE_SCORERS, SkillsStorage, TABLE_SKILLS, TABLE_SKILL_VERSIONS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, WorkspacesStorage, TABLE_WORKSPACES, TABLE_WORKSPACE_VERSIONS, MastraCompositeStore, TraceStatus, transformScoreRow as transformScoreRow$1 } from '@mastra/core/storage';
2
+ import { createVectorErrorId, AgentsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, createStorageErrorId, normalizePerPage, calculatePagination, BlobStore, TABLE_SKILL_BLOBS, MCPClientsStorage, TABLE_MCP_CLIENTS, TABLE_MCP_CLIENT_VERSIONS, MCPServersStorage, TABLE_MCP_SERVERS, TABLE_MCP_SERVER_VERSIONS, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, safelyParseJSON, ObservabilityStorage, TABLE_SPANS, listTracesArgsSchema, toTraceSpans, PromptBlocksStorage, TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS, ScorerDefinitionsStorage, TABLE_SCORER_DEFINITIONS, TABLE_SCORER_DEFINITION_VERSIONS, ScoresStorage, TABLE_SCORERS, SkillsStorage, TABLE_SKILLS, TABLE_SKILL_VERSIONS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, WorkspacesStorage, TABLE_WORKSPACES, TABLE_WORKSPACE_VERSIONS, MastraCompositeStore, TraceStatus, transformScoreRow as transformScoreRow$1 } from '@mastra/core/storage';
3
3
  import { MastraVector, validateUpsertInput, validateVectorValues } from '@mastra/core/vector';
4
4
  import { MongoClient } from 'mongodb';
5
5
  import { v4 } from 'uuid';
@@ -12,7 +12,7 @@ import { saveScorePayloadSchema } from '@mastra/core/evals';
12
12
 
13
13
  // package.json
14
14
  var package_default = {
15
- version: "1.4.0"};
15
+ version: "1.5.0-alpha.0"};
16
16
  var MongoDBFilterTranslator = class extends BaseFilterTranslator {
17
17
  getSupportedOperators() {
18
18
  return {
@@ -2228,6 +2228,559 @@ var MongoDBMCPClientsStorage = class _MongoDBMCPClientsStorage extends MCPClient
2228
2228
  return result;
2229
2229
  }
2230
2230
  };
2231
+ var SNAPSHOT_FIELDS3 = [
2232
+ "name",
2233
+ "version",
2234
+ "description",
2235
+ "instructions",
2236
+ "repository",
2237
+ "releaseDate",
2238
+ "isLatest",
2239
+ "packageCanonical",
2240
+ "tools",
2241
+ "agents",
2242
+ "workflows"
2243
+ ];
2244
+ var MongoDBMCPServersStorage = class _MongoDBMCPServersStorage extends MCPServersStorage {
2245
+ #connector;
2246
+ #skipDefaultIndexes;
2247
+ #indexes;
2248
+ static MANAGED_COLLECTIONS = [TABLE_MCP_SERVERS, TABLE_MCP_SERVER_VERSIONS];
2249
+ constructor(config) {
2250
+ super();
2251
+ this.#connector = resolveMongoDBConfig(config);
2252
+ this.#skipDefaultIndexes = config.skipDefaultIndexes;
2253
+ this.#indexes = config.indexes?.filter(
2254
+ (idx) => _MongoDBMCPServersStorage.MANAGED_COLLECTIONS.includes(idx.collection)
2255
+ );
2256
+ }
2257
+ async getCollection(name) {
2258
+ return this.#connector.getCollection(name);
2259
+ }
2260
+ getDefaultIndexDefinitions() {
2261
+ return [
2262
+ { collection: TABLE_MCP_SERVERS, keys: { id: 1 }, options: { unique: true } },
2263
+ { collection: TABLE_MCP_SERVERS, keys: { createdAt: -1 } },
2264
+ { collection: TABLE_MCP_SERVERS, keys: { updatedAt: -1 } },
2265
+ { collection: TABLE_MCP_SERVERS, keys: { authorId: 1 } },
2266
+ { collection: TABLE_MCP_SERVER_VERSIONS, keys: { id: 1 }, options: { unique: true } },
2267
+ {
2268
+ collection: TABLE_MCP_SERVER_VERSIONS,
2269
+ keys: { mcpServerId: 1, versionNumber: -1 },
2270
+ options: { unique: true }
2271
+ },
2272
+ { collection: TABLE_MCP_SERVER_VERSIONS, keys: { mcpServerId: 1, createdAt: -1 } }
2273
+ ];
2274
+ }
2275
+ async createDefaultIndexes() {
2276
+ if (this.#skipDefaultIndexes) {
2277
+ return;
2278
+ }
2279
+ for (const indexDef of this.getDefaultIndexDefinitions()) {
2280
+ try {
2281
+ const collection = await this.getCollection(indexDef.collection);
2282
+ await collection.createIndex(indexDef.keys, indexDef.options);
2283
+ } catch (error) {
2284
+ this.logger?.warn?.(`Failed to create index on ${indexDef.collection}:`, error);
2285
+ }
2286
+ }
2287
+ }
2288
+ async createCustomIndexes() {
2289
+ if (!this.#indexes || this.#indexes.length === 0) {
2290
+ return;
2291
+ }
2292
+ for (const indexDef of this.#indexes) {
2293
+ try {
2294
+ const collection = await this.getCollection(indexDef.collection);
2295
+ await collection.createIndex(indexDef.keys, indexDef.options);
2296
+ } catch (error) {
2297
+ this.logger?.warn?.(`Failed to create custom index on ${indexDef.collection}:`, error);
2298
+ }
2299
+ }
2300
+ }
2301
+ async init() {
2302
+ await this.createDefaultIndexes();
2303
+ await this.createCustomIndexes();
2304
+ }
2305
+ async dangerouslyClearAll() {
2306
+ const versionsCollection = await this.getCollection(TABLE_MCP_SERVER_VERSIONS);
2307
+ await versionsCollection.deleteMany({});
2308
+ const mcpServersCollection = await this.getCollection(TABLE_MCP_SERVERS);
2309
+ await mcpServersCollection.deleteMany({});
2310
+ }
2311
+ // ==========================================================================
2312
+ // MCP Server CRUD
2313
+ // ==========================================================================
2314
+ async getById(id) {
2315
+ try {
2316
+ const collection = await this.getCollection(TABLE_MCP_SERVERS);
2317
+ const result = await collection.findOne({ id });
2318
+ if (!result) {
2319
+ return null;
2320
+ }
2321
+ return this.transformMCPServer(result);
2322
+ } catch (error) {
2323
+ if (error instanceof MastraError) throw error;
2324
+ throw new MastraError(
2325
+ {
2326
+ id: createStorageErrorId("MONGODB", "GET_MCP_SERVER_BY_ID", "FAILED"),
2327
+ domain: ErrorDomain.STORAGE,
2328
+ category: ErrorCategory.THIRD_PARTY,
2329
+ details: { id }
2330
+ },
2331
+ error
2332
+ );
2333
+ }
2334
+ }
2335
+ async create(input) {
2336
+ const { mcpServer } = input;
2337
+ try {
2338
+ const collection = await this.getCollection(TABLE_MCP_SERVERS);
2339
+ const existing = await collection.findOne({ id: mcpServer.id });
2340
+ if (existing) {
2341
+ throw new MastraError({
2342
+ id: createStorageErrorId("MONGODB", "CREATE_MCP_SERVER", "ALREADY_EXISTS"),
2343
+ domain: ErrorDomain.STORAGE,
2344
+ category: ErrorCategory.USER,
2345
+ details: { id: mcpServer.id },
2346
+ text: `MCP server with id ${mcpServer.id} already exists`
2347
+ });
2348
+ }
2349
+ const now = /* @__PURE__ */ new Date();
2350
+ const newMCPServer = {
2351
+ id: mcpServer.id,
2352
+ status: "draft",
2353
+ activeVersionId: void 0,
2354
+ authorId: mcpServer.authorId,
2355
+ metadata: mcpServer.metadata,
2356
+ createdAt: now,
2357
+ updatedAt: now
2358
+ };
2359
+ await collection.insertOne(this.serializeMCPServer(newMCPServer));
2360
+ const snapshotConfig = {};
2361
+ for (const field of SNAPSHOT_FIELDS3) {
2362
+ if (mcpServer[field] !== void 0) {
2363
+ snapshotConfig[field] = mcpServer[field];
2364
+ }
2365
+ }
2366
+ const versionId = randomUUID();
2367
+ try {
2368
+ await this.createVersion({
2369
+ id: versionId,
2370
+ mcpServerId: mcpServer.id,
2371
+ versionNumber: 1,
2372
+ ...snapshotConfig,
2373
+ changedFields: Object.keys(snapshotConfig),
2374
+ changeMessage: "Initial version"
2375
+ });
2376
+ } catch (versionError) {
2377
+ await collection.deleteOne({ id: mcpServer.id });
2378
+ throw versionError;
2379
+ }
2380
+ return newMCPServer;
2381
+ } catch (error) {
2382
+ if (error instanceof MastraError) {
2383
+ throw error;
2384
+ }
2385
+ throw new MastraError(
2386
+ {
2387
+ id: createStorageErrorId("MONGODB", "CREATE_MCP_SERVER", "FAILED"),
2388
+ domain: ErrorDomain.STORAGE,
2389
+ category: ErrorCategory.THIRD_PARTY,
2390
+ details: { id: mcpServer.id }
2391
+ },
2392
+ error
2393
+ );
2394
+ }
2395
+ }
2396
+ async update(input) {
2397
+ const { id, ...updates } = input;
2398
+ try {
2399
+ const collection = await this.getCollection(TABLE_MCP_SERVERS);
2400
+ const existingMCPServer = await collection.findOne({ id });
2401
+ if (!existingMCPServer) {
2402
+ throw new MastraError({
2403
+ id: createStorageErrorId("MONGODB", "UPDATE_MCP_SERVER", "NOT_FOUND"),
2404
+ domain: ErrorDomain.STORAGE,
2405
+ category: ErrorCategory.USER,
2406
+ details: { id },
2407
+ text: `MCP server with id ${id} not found`
2408
+ });
2409
+ }
2410
+ const updateDoc = {
2411
+ updatedAt: /* @__PURE__ */ new Date()
2412
+ };
2413
+ const metadataFields = {
2414
+ authorId: updates.authorId,
2415
+ activeVersionId: updates.activeVersionId,
2416
+ metadata: updates.metadata,
2417
+ status: updates.status
2418
+ };
2419
+ if (metadataFields.authorId !== void 0) updateDoc.authorId = metadataFields.authorId;
2420
+ if (metadataFields.activeVersionId !== void 0) {
2421
+ updateDoc.activeVersionId = metadataFields.activeVersionId;
2422
+ }
2423
+ if (metadataFields.status !== void 0) {
2424
+ updateDoc.status = metadataFields.status;
2425
+ }
2426
+ if (metadataFields.metadata !== void 0) {
2427
+ const existingMetadata = existingMCPServer.metadata || {};
2428
+ updateDoc.metadata = { ...existingMetadata, ...metadataFields.metadata };
2429
+ }
2430
+ await collection.updateOne({ id }, { $set: updateDoc });
2431
+ const updatedMCPServer = await collection.findOne({ id });
2432
+ if (!updatedMCPServer) {
2433
+ throw new MastraError({
2434
+ id: createStorageErrorId("MONGODB", "UPDATE_MCP_SERVER", "NOT_FOUND_AFTER_UPDATE"),
2435
+ domain: ErrorDomain.STORAGE,
2436
+ category: ErrorCategory.SYSTEM,
2437
+ text: `MCP server with id ${id} was deleted during update`,
2438
+ details: { id }
2439
+ });
2440
+ }
2441
+ return this.transformMCPServer(updatedMCPServer);
2442
+ } catch (error) {
2443
+ if (error instanceof MastraError) {
2444
+ throw error;
2445
+ }
2446
+ throw new MastraError(
2447
+ {
2448
+ id: createStorageErrorId("MONGODB", "UPDATE_MCP_SERVER", "FAILED"),
2449
+ domain: ErrorDomain.STORAGE,
2450
+ category: ErrorCategory.THIRD_PARTY,
2451
+ details: { id }
2452
+ },
2453
+ error
2454
+ );
2455
+ }
2456
+ }
2457
+ async delete(id) {
2458
+ try {
2459
+ await this.deleteVersionsByParentId(id);
2460
+ const collection = await this.getCollection(TABLE_MCP_SERVERS);
2461
+ await collection.deleteOne({ id });
2462
+ } catch (error) {
2463
+ if (error instanceof MastraError) throw error;
2464
+ throw new MastraError(
2465
+ {
2466
+ id: createStorageErrorId("MONGODB", "DELETE_MCP_SERVER", "FAILED"),
2467
+ domain: ErrorDomain.STORAGE,
2468
+ category: ErrorCategory.THIRD_PARTY,
2469
+ details: { id }
2470
+ },
2471
+ error
2472
+ );
2473
+ }
2474
+ }
2475
+ async list(args) {
2476
+ try {
2477
+ const { page = 0, perPage: perPageInput, orderBy, authorId, metadata, status = "published" } = args || {};
2478
+ const { field, direction } = this.parseOrderBy(orderBy);
2479
+ if (page < 0) {
2480
+ throw new MastraError(
2481
+ {
2482
+ id: createStorageErrorId("MONGODB", "LIST_MCP_SERVERS", "INVALID_PAGE"),
2483
+ domain: ErrorDomain.STORAGE,
2484
+ category: ErrorCategory.USER,
2485
+ details: { page }
2486
+ },
2487
+ new Error("page must be >= 0")
2488
+ );
2489
+ }
2490
+ const perPage = normalizePerPage(perPageInput, 100);
2491
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2492
+ const collection = await this.getCollection(TABLE_MCP_SERVERS);
2493
+ const filter = {};
2494
+ filter.status = status;
2495
+ if (authorId) {
2496
+ filter.authorId = authorId;
2497
+ }
2498
+ if (metadata) {
2499
+ for (const [key, value] of Object.entries(metadata)) {
2500
+ filter[`metadata.${key}`] = value;
2501
+ }
2502
+ }
2503
+ const total = await collection.countDocuments(filter);
2504
+ if (total === 0 || perPage === 0) {
2505
+ return {
2506
+ mcpServers: [],
2507
+ total,
2508
+ page,
2509
+ perPage: perPageForResponse,
2510
+ hasMore: false
2511
+ };
2512
+ }
2513
+ const sortOrder = direction === "ASC" ? 1 : -1;
2514
+ let cursor = collection.find(filter).sort({ [field]: sortOrder }).skip(offset);
2515
+ if (perPageInput !== false) {
2516
+ cursor = cursor.limit(perPage);
2517
+ }
2518
+ const results = await cursor.toArray();
2519
+ const mcpServers = results.map((doc) => this.transformMCPServer(doc));
2520
+ return {
2521
+ mcpServers,
2522
+ total,
2523
+ page,
2524
+ perPage: perPageForResponse,
2525
+ hasMore: perPageInput !== false && offset + perPage < total
2526
+ };
2527
+ } catch (error) {
2528
+ if (error instanceof MastraError) {
2529
+ throw error;
2530
+ }
2531
+ throw new MastraError(
2532
+ {
2533
+ id: createStorageErrorId("MONGODB", "LIST_MCP_SERVERS", "FAILED"),
2534
+ domain: ErrorDomain.STORAGE,
2535
+ category: ErrorCategory.THIRD_PARTY
2536
+ },
2537
+ error
2538
+ );
2539
+ }
2540
+ }
2541
+ // ==========================================================================
2542
+ // MCP Server Version Methods
2543
+ // ==========================================================================
2544
+ async createVersion(input) {
2545
+ try {
2546
+ const collection = await this.getCollection(TABLE_MCP_SERVER_VERSIONS);
2547
+ const now = /* @__PURE__ */ new Date();
2548
+ const versionDoc = {
2549
+ id: input.id,
2550
+ mcpServerId: input.mcpServerId,
2551
+ versionNumber: input.versionNumber,
2552
+ changedFields: input.changedFields ?? void 0,
2553
+ changeMessage: input.changeMessage ?? void 0,
2554
+ createdAt: now
2555
+ };
2556
+ for (const field of SNAPSHOT_FIELDS3) {
2557
+ if (input[field] !== void 0) {
2558
+ versionDoc[field] = input[field];
2559
+ }
2560
+ }
2561
+ await collection.insertOne(versionDoc);
2562
+ return {
2563
+ ...input,
2564
+ createdAt: now
2565
+ };
2566
+ } catch (error) {
2567
+ throw new MastraError(
2568
+ {
2569
+ id: createStorageErrorId("MONGODB", "CREATE_MCP_SERVER_VERSION", "FAILED"),
2570
+ domain: ErrorDomain.STORAGE,
2571
+ category: ErrorCategory.THIRD_PARTY,
2572
+ details: { versionId: input.id, mcpServerId: input.mcpServerId }
2573
+ },
2574
+ error
2575
+ );
2576
+ }
2577
+ }
2578
+ async getVersion(id) {
2579
+ try {
2580
+ const collection = await this.getCollection(TABLE_MCP_SERVER_VERSIONS);
2581
+ const result = await collection.findOne({ id });
2582
+ if (!result) {
2583
+ return null;
2584
+ }
2585
+ return this.transformVersion(result);
2586
+ } catch (error) {
2587
+ throw new MastraError(
2588
+ {
2589
+ id: createStorageErrorId("MONGODB", "GET_MCP_SERVER_VERSION", "FAILED"),
2590
+ domain: ErrorDomain.STORAGE,
2591
+ category: ErrorCategory.THIRD_PARTY,
2592
+ details: { versionId: id }
2593
+ },
2594
+ error
2595
+ );
2596
+ }
2597
+ }
2598
+ async getVersionByNumber(mcpServerId, versionNumber) {
2599
+ try {
2600
+ const collection = await this.getCollection(TABLE_MCP_SERVER_VERSIONS);
2601
+ const result = await collection.findOne({ mcpServerId, versionNumber });
2602
+ if (!result) {
2603
+ return null;
2604
+ }
2605
+ return this.transformVersion(result);
2606
+ } catch (error) {
2607
+ throw new MastraError(
2608
+ {
2609
+ id: createStorageErrorId("MONGODB", "GET_MCP_SERVER_VERSION_BY_NUMBER", "FAILED"),
2610
+ domain: ErrorDomain.STORAGE,
2611
+ category: ErrorCategory.THIRD_PARTY,
2612
+ details: { mcpServerId, versionNumber }
2613
+ },
2614
+ error
2615
+ );
2616
+ }
2617
+ }
2618
+ async getLatestVersion(mcpServerId) {
2619
+ try {
2620
+ const collection = await this.getCollection(TABLE_MCP_SERVER_VERSIONS);
2621
+ const result = await collection.find({ mcpServerId }).sort({ versionNumber: -1 }).limit(1).toArray();
2622
+ if (!result || result.length === 0) {
2623
+ return null;
2624
+ }
2625
+ return this.transformVersion(result[0]);
2626
+ } catch (error) {
2627
+ throw new MastraError(
2628
+ {
2629
+ id: createStorageErrorId("MONGODB", "GET_LATEST_MCP_SERVER_VERSION", "FAILED"),
2630
+ domain: ErrorDomain.STORAGE,
2631
+ category: ErrorCategory.THIRD_PARTY,
2632
+ details: { mcpServerId }
2633
+ },
2634
+ error
2635
+ );
2636
+ }
2637
+ }
2638
+ async listVersions(input) {
2639
+ const { mcpServerId, page = 0, perPage: perPageInput, orderBy } = input;
2640
+ if (page < 0) {
2641
+ throw new MastraError(
2642
+ {
2643
+ id: createStorageErrorId("MONGODB", "LIST_MCP_SERVER_VERSIONS", "INVALID_PAGE"),
2644
+ domain: ErrorDomain.STORAGE,
2645
+ category: ErrorCategory.USER,
2646
+ details: { page }
2647
+ },
2648
+ new Error("page must be >= 0")
2649
+ );
2650
+ }
2651
+ const perPage = normalizePerPage(perPageInput, 20);
2652
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2653
+ try {
2654
+ const { field, direction } = this.parseVersionOrderBy(orderBy);
2655
+ const collection = await this.getCollection(TABLE_MCP_SERVER_VERSIONS);
2656
+ const total = await collection.countDocuments({ mcpServerId });
2657
+ if (total === 0 || perPage === 0) {
2658
+ return {
2659
+ versions: [],
2660
+ total,
2661
+ page,
2662
+ perPage: perPageForResponse,
2663
+ hasMore: false
2664
+ };
2665
+ }
2666
+ const sortOrder = direction === "ASC" ? 1 : -1;
2667
+ let cursor = collection.find({ mcpServerId }).sort({ [field]: sortOrder }).skip(offset);
2668
+ if (perPageInput !== false) {
2669
+ cursor = cursor.limit(perPage);
2670
+ }
2671
+ const results = await cursor.toArray();
2672
+ const versions = results.map((doc) => this.transformVersion(doc));
2673
+ return {
2674
+ versions,
2675
+ total,
2676
+ page,
2677
+ perPage: perPageForResponse,
2678
+ hasMore: perPageInput !== false && offset + perPage < total
2679
+ };
2680
+ } catch (error) {
2681
+ throw new MastraError(
2682
+ {
2683
+ id: createStorageErrorId("MONGODB", "LIST_MCP_SERVER_VERSIONS", "FAILED"),
2684
+ domain: ErrorDomain.STORAGE,
2685
+ category: ErrorCategory.THIRD_PARTY,
2686
+ details: { mcpServerId }
2687
+ },
2688
+ error
2689
+ );
2690
+ }
2691
+ }
2692
+ async deleteVersion(id) {
2693
+ try {
2694
+ const collection = await this.getCollection(TABLE_MCP_SERVER_VERSIONS);
2695
+ await collection.deleteOne({ id });
2696
+ } catch (error) {
2697
+ throw new MastraError(
2698
+ {
2699
+ id: createStorageErrorId("MONGODB", "DELETE_MCP_SERVER_VERSION", "FAILED"),
2700
+ domain: ErrorDomain.STORAGE,
2701
+ category: ErrorCategory.THIRD_PARTY,
2702
+ details: { versionId: id }
2703
+ },
2704
+ error
2705
+ );
2706
+ }
2707
+ }
2708
+ async deleteVersionsByParentId(mcpServerId) {
2709
+ try {
2710
+ const collection = await this.getCollection(TABLE_MCP_SERVER_VERSIONS);
2711
+ await collection.deleteMany({ mcpServerId });
2712
+ } catch (error) {
2713
+ throw new MastraError(
2714
+ {
2715
+ id: createStorageErrorId("MONGODB", "DELETE_VERSIONS_BY_MCP_SERVER_ID", "FAILED"),
2716
+ domain: ErrorDomain.STORAGE,
2717
+ category: ErrorCategory.THIRD_PARTY,
2718
+ details: { mcpServerId }
2719
+ },
2720
+ error
2721
+ );
2722
+ }
2723
+ }
2724
+ async countVersions(mcpServerId) {
2725
+ try {
2726
+ const collection = await this.getCollection(TABLE_MCP_SERVER_VERSIONS);
2727
+ return await collection.countDocuments({ mcpServerId });
2728
+ } catch (error) {
2729
+ throw new MastraError(
2730
+ {
2731
+ id: createStorageErrorId("MONGODB", "COUNT_MCP_SERVER_VERSIONS", "FAILED"),
2732
+ domain: ErrorDomain.STORAGE,
2733
+ category: ErrorCategory.THIRD_PARTY,
2734
+ details: { mcpServerId }
2735
+ },
2736
+ error
2737
+ );
2738
+ }
2739
+ }
2740
+ // ==========================================================================
2741
+ // Private Helper Methods
2742
+ // ==========================================================================
2743
+ transformMCPServer(doc) {
2744
+ const { _id, ...rest } = doc;
2745
+ return {
2746
+ id: rest.id,
2747
+ status: rest.status,
2748
+ activeVersionId: rest.activeVersionId,
2749
+ authorId: rest.authorId,
2750
+ metadata: rest.metadata,
2751
+ createdAt: rest.createdAt instanceof Date ? rest.createdAt : new Date(rest.createdAt),
2752
+ updatedAt: rest.updatedAt instanceof Date ? rest.updatedAt : new Date(rest.updatedAt)
2753
+ };
2754
+ }
2755
+ serializeMCPServer(mcpServer) {
2756
+ return {
2757
+ id: mcpServer.id,
2758
+ status: mcpServer.status,
2759
+ activeVersionId: mcpServer.activeVersionId,
2760
+ authorId: mcpServer.authorId,
2761
+ metadata: mcpServer.metadata,
2762
+ createdAt: mcpServer.createdAt,
2763
+ updatedAt: mcpServer.updatedAt
2764
+ };
2765
+ }
2766
+ transformVersion(doc) {
2767
+ const { _id, ...version } = doc;
2768
+ const result = {
2769
+ id: version.id,
2770
+ mcpServerId: version.mcpServerId,
2771
+ versionNumber: version.versionNumber,
2772
+ changedFields: version.changedFields,
2773
+ changeMessage: version.changeMessage,
2774
+ createdAt: version.createdAt instanceof Date ? version.createdAt : new Date(version.createdAt)
2775
+ };
2776
+ for (const field of SNAPSHOT_FIELDS3) {
2777
+ if (version[field] !== void 0) {
2778
+ result[field] = version[field];
2779
+ }
2780
+ }
2781
+ return result;
2782
+ }
2783
+ };
2231
2784
  function formatDateForMongoDB(date) {
2232
2785
  return typeof date === "string" ? new Date(date) : date;
2233
2786
  }
@@ -3602,32 +4155,40 @@ var MemoryStorageMongoDB = class _MemoryStorageMongoDB extends MemoryStorage {
3602
4155
  const retentionFloor = input.messageTokensThreshold * (1 - input.activationRatio);
3603
4156
  const targetMessageTokens = Math.max(0, input.currentPendingTokens - retentionFloor);
3604
4157
  let cumulativeMessageTokens = 0;
3605
- let bestBoundary = 0;
3606
- let bestBoundaryMessageTokens = 0;
4158
+ let bestOverBoundary = 0;
4159
+ let bestOverTokens = 0;
4160
+ let bestUnderBoundary = 0;
4161
+ let bestUnderTokens = 0;
3607
4162
  for (let i = 0; i < chunks.length; i++) {
3608
4163
  cumulativeMessageTokens += chunks[i].messageTokens ?? 0;
3609
4164
  const boundary = i + 1;
3610
- const isUnder = cumulativeMessageTokens <= targetMessageTokens;
3611
- const bestIsUnder = bestBoundaryMessageTokens <= targetMessageTokens;
3612
- if (bestBoundary === 0) {
3613
- bestBoundary = boundary;
3614
- bestBoundaryMessageTokens = cumulativeMessageTokens;
3615
- } else if (isUnder && !bestIsUnder) {
3616
- bestBoundary = boundary;
3617
- bestBoundaryMessageTokens = cumulativeMessageTokens;
3618
- } else if (isUnder && bestIsUnder) {
3619
- if (cumulativeMessageTokens > bestBoundaryMessageTokens) {
3620
- bestBoundary = boundary;
3621
- bestBoundaryMessageTokens = cumulativeMessageTokens;
4165
+ if (cumulativeMessageTokens >= targetMessageTokens) {
4166
+ if (bestOverBoundary === 0 || cumulativeMessageTokens < bestOverTokens) {
4167
+ bestOverBoundary = boundary;
4168
+ bestOverTokens = cumulativeMessageTokens;
3622
4169
  }
3623
- } else if (!isUnder && !bestIsUnder) {
3624
- if (cumulativeMessageTokens < bestBoundaryMessageTokens) {
3625
- bestBoundary = boundary;
3626
- bestBoundaryMessageTokens = cumulativeMessageTokens;
4170
+ } else {
4171
+ if (cumulativeMessageTokens > bestUnderTokens) {
4172
+ bestUnderBoundary = boundary;
4173
+ bestUnderTokens = cumulativeMessageTokens;
3627
4174
  }
3628
4175
  }
3629
4176
  }
3630
- const chunksToActivate = bestBoundary === 0 ? 1 : bestBoundary;
4177
+ const maxOvershoot = retentionFloor * 0.95;
4178
+ const overshoot = bestOverTokens - targetMessageTokens;
4179
+ const remainingAfterOver = input.currentPendingTokens - bestOverTokens;
4180
+ let chunksToActivate;
4181
+ if (input.forceMaxActivation && bestOverBoundary > 0) {
4182
+ chunksToActivate = bestOverBoundary;
4183
+ } else if (bestOverBoundary > 0 && overshoot <= maxOvershoot && (remainingAfterOver >= 1e3 || retentionFloor === 0)) {
4184
+ chunksToActivate = bestOverBoundary;
4185
+ } else if (bestUnderBoundary > 0) {
4186
+ chunksToActivate = bestUnderBoundary;
4187
+ } else if (bestOverBoundary > 0) {
4188
+ chunksToActivate = bestOverBoundary;
4189
+ } else {
4190
+ chunksToActivate = 1;
4191
+ }
3631
4192
  const activatedChunks = chunks.slice(0, chunksToActivate);
3632
4193
  const remainingChunks = chunks.slice(chunksToActivate);
3633
4194
  const activatedContent = activatedChunks.map((c) => c.observations).join("\n\n");
@@ -3659,6 +4220,7 @@ ${activatedContent}` : activatedContent;
3659
4220
  }
3660
4221
  }
3661
4222
  );
4223
+ const latestChunkHints = activatedChunks[activatedChunks.length - 1];
3662
4224
  return {
3663
4225
  chunksActivated: activatedChunks.length,
3664
4226
  messageTokensActivated: activatedMessageTokens,
@@ -3673,7 +4235,9 @@ ${activatedContent}` : activatedContent;
3673
4235
  observationTokens: c.tokenCount,
3674
4236
  messageCount: c.messageIds.length,
3675
4237
  observations: c.observations
3676
- }))
4238
+ })),
4239
+ suggestedContinuation: latestChunkHints?.suggestedContinuation ?? void 0,
4240
+ currentTask: latestChunkHints?.currentTask ?? void 0
3677
4241
  };
3678
4242
  } catch (error) {
3679
4243
  if (error instanceof MastraError) {
@@ -4571,7 +5135,7 @@ Note: This migration may take some time for large collections.
4571
5135
  return span;
4572
5136
  }
4573
5137
  };
4574
- var SNAPSHOT_FIELDS3 = ["name", "description", "content", "rules"];
5138
+ var SNAPSHOT_FIELDS4 = ["name", "description", "content", "rules"];
4575
5139
  var MongoDBPromptBlocksStorage = class _MongoDBPromptBlocksStorage extends PromptBlocksStorage {
4576
5140
  #connector;
4577
5141
  #skipDefaultIndexes;
@@ -4688,7 +5252,7 @@ var MongoDBPromptBlocksStorage = class _MongoDBPromptBlocksStorage extends Promp
4688
5252
  };
4689
5253
  await collection.insertOne(this.serializeBlock(newBlock));
4690
5254
  const snapshotConfig = {};
4691
- for (const field of SNAPSHOT_FIELDS3) {
5255
+ for (const field of SNAPSHOT_FIELDS4) {
4692
5256
  if (promptBlock[field] !== void 0) {
4693
5257
  snapshotConfig[field] = promptBlock[field];
4694
5258
  }
@@ -4877,7 +5441,7 @@ var MongoDBPromptBlocksStorage = class _MongoDBPromptBlocksStorage extends Promp
4877
5441
  changeMessage: input.changeMessage ?? void 0,
4878
5442
  createdAt: now
4879
5443
  };
4880
- for (const field of SNAPSHOT_FIELDS3) {
5444
+ for (const field of SNAPSHOT_FIELDS4) {
4881
5445
  if (input[field] !== void 0) {
4882
5446
  versionDoc[field] = input[field];
4883
5447
  }
@@ -5097,7 +5661,7 @@ var MongoDBPromptBlocksStorage = class _MongoDBPromptBlocksStorage extends Promp
5097
5661
  changeMessage: version.changeMessage,
5098
5662
  createdAt: version.createdAt instanceof Date ? version.createdAt : new Date(version.createdAt)
5099
5663
  };
5100
- for (const field of SNAPSHOT_FIELDS3) {
5664
+ for (const field of SNAPSHOT_FIELDS4) {
5101
5665
  if (version[field] !== void 0) {
5102
5666
  result[field] = version[field];
5103
5667
  }
@@ -5105,7 +5669,7 @@ var MongoDBPromptBlocksStorage = class _MongoDBPromptBlocksStorage extends Promp
5105
5669
  return result;
5106
5670
  }
5107
5671
  };
5108
- var SNAPSHOT_FIELDS4 = [
5672
+ var SNAPSHOT_FIELDS5 = [
5109
5673
  "name",
5110
5674
  "description",
5111
5675
  "type",
@@ -5231,7 +5795,7 @@ var MongoDBScorerDefinitionsStorage = class _MongoDBScorerDefinitionsStorage ext
5231
5795
  };
5232
5796
  await collection.insertOne(this.serializeScorerDefinition(newScorerDefinition));
5233
5797
  const snapshotConfig = {};
5234
- for (const field of SNAPSHOT_FIELDS4) {
5798
+ for (const field of SNAPSHOT_FIELDS5) {
5235
5799
  if (scorerDefinition[field] !== void 0) {
5236
5800
  snapshotConfig[field] = scorerDefinition[field];
5237
5801
  }
@@ -5422,7 +5986,7 @@ var MongoDBScorerDefinitionsStorage = class _MongoDBScorerDefinitionsStorage ext
5422
5986
  changeMessage: input.changeMessage ?? void 0,
5423
5987
  createdAt: now
5424
5988
  };
5425
- for (const field of SNAPSHOT_FIELDS4) {
5989
+ for (const field of SNAPSHOT_FIELDS5) {
5426
5990
  if (input[field] !== void 0) {
5427
5991
  versionDoc[field] = input[field];
5428
5992
  }
@@ -5642,7 +6206,7 @@ var MongoDBScorerDefinitionsStorage = class _MongoDBScorerDefinitionsStorage ext
5642
6206
  changeMessage: version.changeMessage,
5643
6207
  createdAt: version.createdAt instanceof Date ? version.createdAt : new Date(version.createdAt)
5644
6208
  };
5645
- for (const field of SNAPSHOT_FIELDS4) {
6209
+ for (const field of SNAPSHOT_FIELDS5) {
5646
6210
  if (version[field] !== void 0) {
5647
6211
  result[field] = version[field];
5648
6212
  }
@@ -6018,7 +6582,7 @@ var ScoresStorageMongoDB = class _ScoresStorageMongoDB extends ScoresStorage {
6018
6582
  }
6019
6583
  }
6020
6584
  };
6021
- var SNAPSHOT_FIELDS5 = [
6585
+ var SNAPSHOT_FIELDS6 = [
6022
6586
  "name",
6023
6587
  "description",
6024
6588
  "instructions",
@@ -6147,7 +6711,7 @@ var MongoDBSkillsStorage = class _MongoDBSkillsStorage extends SkillsStorage {
6147
6711
  };
6148
6712
  await collection.insertOne(this.serializeSkill(newSkill));
6149
6713
  const snapshotConfig = {};
6150
- for (const field of SNAPSHOT_FIELDS5) {
6714
+ for (const field of SNAPSHOT_FIELDS6) {
6151
6715
  if (skill[field] !== void 0) {
6152
6716
  snapshotConfig[field] = skill[field];
6153
6717
  }
@@ -6205,7 +6769,7 @@ var MongoDBSkillsStorage = class _MongoDBSkillsStorage extends SkillsStorage {
6205
6769
  status: updates.status
6206
6770
  };
6207
6771
  const configFields = {};
6208
- for (const field of SNAPSHOT_FIELDS5) {
6772
+ for (const field of SNAPSHOT_FIELDS6) {
6209
6773
  if (updates[field] !== void 0) {
6210
6774
  configFields[field] = updates[field];
6211
6775
  }
@@ -6366,7 +6930,7 @@ var MongoDBSkillsStorage = class _MongoDBSkillsStorage extends SkillsStorage {
6366
6930
  changeMessage: input.changeMessage ?? void 0,
6367
6931
  createdAt: now
6368
6932
  };
6369
- for (const field of SNAPSHOT_FIELDS5) {
6933
+ for (const field of SNAPSHOT_FIELDS6) {
6370
6934
  if (input[field] !== void 0) {
6371
6935
  versionDoc[field] = input[field];
6372
6936
  }
@@ -6584,7 +7148,7 @@ var MongoDBSkillsStorage = class _MongoDBSkillsStorage extends SkillsStorage {
6584
7148
  changeMessage: version.changeMessage,
6585
7149
  createdAt: version.createdAt instanceof Date ? version.createdAt : new Date(version.createdAt)
6586
7150
  };
6587
- for (const field of SNAPSHOT_FIELDS5) {
7151
+ for (const field of SNAPSHOT_FIELDS6) {
6588
7152
  if (version[field] !== void 0) {
6589
7153
  result[field] = version[field];
6590
7154
  }
@@ -6593,7 +7157,7 @@ var MongoDBSkillsStorage = class _MongoDBSkillsStorage extends SkillsStorage {
6593
7157
  }
6594
7158
  extractSnapshotFields(version) {
6595
7159
  const result = {};
6596
- for (const field of SNAPSHOT_FIELDS5) {
7160
+ for (const field of SNAPSHOT_FIELDS6) {
6597
7161
  if (version[field] !== void 0) {
6598
7162
  result[field] = version[field];
6599
7163
  }
@@ -6879,7 +7443,7 @@ var WorkflowsStorageMongoDB = class _WorkflowsStorageMongoDB extends WorkflowsSt
6879
7443
  };
6880
7444
  }
6881
7445
  };
6882
- var SNAPSHOT_FIELDS6 = [
7446
+ var SNAPSHOT_FIELDS7 = [
6883
7447
  "name",
6884
7448
  "description",
6885
7449
  "filesystem",
@@ -7018,7 +7582,7 @@ var MongoDBWorkspacesStorage = class _MongoDBWorkspacesStorage extends Workspace
7018
7582
  };
7019
7583
  await collection.insertOne(this.serializeWorkspace(newWorkspace));
7020
7584
  const snapshotConfig = {};
7021
- for (const field of SNAPSHOT_FIELDS6) {
7585
+ for (const field of SNAPSHOT_FIELDS7) {
7022
7586
  if (workspace[field] !== void 0) {
7023
7587
  snapshotConfig[field] = workspace[field];
7024
7588
  }
@@ -7077,7 +7641,7 @@ var MongoDBWorkspacesStorage = class _MongoDBWorkspacesStorage extends Workspace
7077
7641
  status: updates.status
7078
7642
  };
7079
7643
  const configFields = {};
7080
- for (const field of SNAPSHOT_FIELDS6) {
7644
+ for (const field of SNAPSHOT_FIELDS7) {
7081
7645
  if (updates[field] !== void 0) {
7082
7646
  configFields[field] = updates[field];
7083
7647
  }
@@ -7242,7 +7806,7 @@ var MongoDBWorkspacesStorage = class _MongoDBWorkspacesStorage extends Workspace
7242
7806
  changeMessage: input.changeMessage ?? void 0,
7243
7807
  createdAt: now
7244
7808
  };
7245
- for (const field of SNAPSHOT_FIELDS6) {
7809
+ for (const field of SNAPSHOT_FIELDS7) {
7246
7810
  if (input[field] !== void 0) {
7247
7811
  versionDoc[field] = input[field];
7248
7812
  }
@@ -7462,7 +8026,7 @@ var MongoDBWorkspacesStorage = class _MongoDBWorkspacesStorage extends Workspace
7462
8026
  changeMessage: version.changeMessage,
7463
8027
  createdAt: version.createdAt instanceof Date ? version.createdAt : new Date(version.createdAt)
7464
8028
  };
7465
- for (const field of SNAPSHOT_FIELDS6) {
8029
+ for (const field of SNAPSHOT_FIELDS7) {
7466
8030
  if (version[field] !== void 0) {
7467
8031
  result[field] = version[field];
7468
8032
  }
@@ -7471,7 +8035,7 @@ var MongoDBWorkspacesStorage = class _MongoDBWorkspacesStorage extends Workspace
7471
8035
  }
7472
8036
  extractSnapshotFields(version) {
7473
8037
  const result = {};
7474
- for (const field of SNAPSHOT_FIELDS6) {
8038
+ for (const field of SNAPSHOT_FIELDS7) {
7475
8039
  if (version[field] !== void 0) {
7476
8040
  result[field] = version[field];
7477
8041
  }
@@ -7500,6 +8064,7 @@ var MongoDBStore = class extends MastraCompositeStore {
7500
8064
  const promptBlocks = new MongoDBPromptBlocksStorage(domainConfig);
7501
8065
  const scorerDefinitions = new MongoDBScorerDefinitionsStorage(domainConfig);
7502
8066
  const mcpClients = new MongoDBMCPClientsStorage(domainConfig);
8067
+ const mcpServers = new MongoDBMCPServersStorage(domainConfig);
7503
8068
  const workspaces = new MongoDBWorkspacesStorage(domainConfig);
7504
8069
  const skills = new MongoDBSkillsStorage(domainConfig);
7505
8070
  const blobs = new MongoDBBlobStore(domainConfig);
@@ -7512,6 +8077,7 @@ var MongoDBStore = class extends MastraCompositeStore {
7512
8077
  promptBlocks,
7513
8078
  scorerDefinitions,
7514
8079
  mcpClients,
8080
+ mcpServers,
7515
8081
  workspaces,
7516
8082
  skills,
7517
8083
  blobs
@@ -7633,6 +8199,6 @@ Example Complex Query:
7633
8199
  ]
7634
8200
  }`;
7635
8201
 
7636
- export { MONGODB_PROMPT, MemoryStorageMongoDB, MongoDBAgentsStorage, MongoDBBlobStore, MongoDBMCPClientsStorage, MongoDBPromptBlocksStorage, MongoDBScorerDefinitionsStorage, MongoDBSkillsStorage, MongoDBStore, MongoDBVector, MongoDBWorkspacesStorage, ObservabilityMongoDB, ScoresStorageMongoDB, WorkflowsStorageMongoDB };
8202
+ export { MONGODB_PROMPT, MemoryStorageMongoDB, MongoDBAgentsStorage, MongoDBBlobStore, MongoDBMCPClientsStorage, MongoDBMCPServersStorage, MongoDBPromptBlocksStorage, MongoDBScorerDefinitionsStorage, MongoDBSkillsStorage, MongoDBStore, MongoDBVector, MongoDBWorkspacesStorage, ObservabilityMongoDB, ScoresStorageMongoDB, WorkflowsStorageMongoDB };
7637
8203
  //# sourceMappingURL=index.js.map
7638
8204
  //# sourceMappingURL=index.js.map