@mastra/pg 1.5.0 → 1.6.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.cjs CHANGED
@@ -5986,6 +5986,648 @@ var MCPClientsPG = class _MCPClientsPG extends storage.MCPClientsStorage {
5986
5986
  };
5987
5987
  }
5988
5988
  };
5989
+ var SNAPSHOT_FIELDS2 = [
5990
+ "name",
5991
+ "version",
5992
+ "description",
5993
+ "instructions",
5994
+ "repository",
5995
+ "releaseDate",
5996
+ "isLatest",
5997
+ "packageCanonical",
5998
+ "tools",
5999
+ "agents",
6000
+ "workflows"
6001
+ ];
6002
+ var MCPServersPG = class _MCPServersPG extends storage.MCPServersStorage {
6003
+ #db;
6004
+ #schema;
6005
+ #skipDefaultIndexes;
6006
+ #indexes;
6007
+ static MANAGED_TABLES = [storage.TABLE_MCP_SERVERS, storage.TABLE_MCP_SERVER_VERSIONS];
6008
+ constructor(config) {
6009
+ super();
6010
+ const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
6011
+ this.#db = new PgDB({ client, schemaName, skipDefaultIndexes });
6012
+ this.#schema = schemaName || "public";
6013
+ this.#skipDefaultIndexes = skipDefaultIndexes;
6014
+ this.#indexes = indexes?.filter((idx) => _MCPServersPG.MANAGED_TABLES.includes(idx.table));
6015
+ }
6016
+ getDefaultIndexDefinitions() {
6017
+ return [
6018
+ {
6019
+ name: "idx_mcp_server_versions_server_version",
6020
+ table: storage.TABLE_MCP_SERVER_VERSIONS,
6021
+ columns: ["mcpServerId", "versionNumber"],
6022
+ unique: true
6023
+ }
6024
+ ];
6025
+ }
6026
+ async createDefaultIndexes() {
6027
+ if (this.#skipDefaultIndexes) {
6028
+ return;
6029
+ }
6030
+ for (const indexDef of this.getDefaultIndexDefinitions()) {
6031
+ try {
6032
+ await this.#db.createIndex(indexDef);
6033
+ } catch {
6034
+ }
6035
+ }
6036
+ }
6037
+ async init() {
6038
+ await this.#db.createTable({
6039
+ tableName: storage.TABLE_MCP_SERVERS,
6040
+ schema: storage.TABLE_SCHEMAS[storage.TABLE_MCP_SERVERS]
6041
+ });
6042
+ await this.#db.createTable({
6043
+ tableName: storage.TABLE_MCP_SERVER_VERSIONS,
6044
+ schema: storage.TABLE_SCHEMAS[storage.TABLE_MCP_SERVER_VERSIONS]
6045
+ });
6046
+ await this.createDefaultIndexes();
6047
+ await this.createCustomIndexes();
6048
+ }
6049
+ async createCustomIndexes() {
6050
+ if (!this.#indexes || this.#indexes.length === 0) {
6051
+ return;
6052
+ }
6053
+ for (const indexDef of this.#indexes) {
6054
+ try {
6055
+ await this.#db.createIndex(indexDef);
6056
+ } catch (error) {
6057
+ this.logger?.warn?.(`Failed to create custom index ${indexDef.name}:`, error);
6058
+ }
6059
+ }
6060
+ }
6061
+ async dangerouslyClearAll() {
6062
+ await this.#db.clearTable({ tableName: storage.TABLE_MCP_SERVER_VERSIONS });
6063
+ await this.#db.clearTable({ tableName: storage.TABLE_MCP_SERVERS });
6064
+ }
6065
+ // ==========================================================================
6066
+ // MCP Server CRUD Methods
6067
+ // ==========================================================================
6068
+ async getById(id) {
6069
+ try {
6070
+ const tableName = getTableName2({ indexName: storage.TABLE_MCP_SERVERS, schemaName: getSchemaName2(this.#schema) });
6071
+ const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
6072
+ if (!result) {
6073
+ return null;
6074
+ }
6075
+ return this.parseMCPServerRow(result);
6076
+ } catch (error$1) {
6077
+ if (error$1 instanceof error.MastraError) throw error$1;
6078
+ throw new error.MastraError(
6079
+ {
6080
+ id: storage.createStorageErrorId("PG", "GET_MCP_SERVER_BY_ID", "FAILED"),
6081
+ domain: error.ErrorDomain.STORAGE,
6082
+ category: error.ErrorCategory.THIRD_PARTY,
6083
+ details: { mcpServerId: id }
6084
+ },
6085
+ error$1
6086
+ );
6087
+ }
6088
+ }
6089
+ async create(input) {
6090
+ const { mcpServer } = input;
6091
+ try {
6092
+ const tableName = getTableName2({ indexName: storage.TABLE_MCP_SERVERS, schemaName: getSchemaName2(this.#schema) });
6093
+ const now = /* @__PURE__ */ new Date();
6094
+ const nowIso = now.toISOString();
6095
+ await this.#db.client.none(
6096
+ `INSERT INTO ${tableName} (
6097
+ id, status, "activeVersionId", "authorId", metadata,
6098
+ "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
6099
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
6100
+ [
6101
+ mcpServer.id,
6102
+ "draft",
6103
+ null,
6104
+ mcpServer.authorId ?? null,
6105
+ mcpServer.metadata ? JSON.stringify(mcpServer.metadata) : null,
6106
+ nowIso,
6107
+ nowIso,
6108
+ nowIso,
6109
+ nowIso
6110
+ ]
6111
+ );
6112
+ const { id: _id, authorId: _authorId, metadata: _metadata, ...snapshotConfig } = mcpServer;
6113
+ const versionId = crypto.randomUUID();
6114
+ await this.createVersion({
6115
+ id: versionId,
6116
+ mcpServerId: mcpServer.id,
6117
+ versionNumber: 1,
6118
+ ...snapshotConfig,
6119
+ changedFields: [...SNAPSHOT_FIELDS2],
6120
+ changeMessage: "Initial version"
6121
+ });
6122
+ return {
6123
+ id: mcpServer.id,
6124
+ status: "draft",
6125
+ activeVersionId: void 0,
6126
+ authorId: mcpServer.authorId,
6127
+ metadata: mcpServer.metadata,
6128
+ createdAt: now,
6129
+ updatedAt: now
6130
+ };
6131
+ } catch (error$1) {
6132
+ try {
6133
+ const tableName = getTableName2({
6134
+ indexName: storage.TABLE_MCP_SERVERS,
6135
+ schemaName: getSchemaName2(this.#schema)
6136
+ });
6137
+ await this.#db.client.none(
6138
+ `DELETE FROM ${tableName} WHERE id = $1 AND status = 'draft' AND "activeVersionId" IS NULL`,
6139
+ [mcpServer.id]
6140
+ );
6141
+ } catch {
6142
+ }
6143
+ if (error$1 instanceof error.MastraError) throw error$1;
6144
+ throw new error.MastraError(
6145
+ {
6146
+ id: storage.createStorageErrorId("PG", "CREATE_MCP_SERVER", "FAILED"),
6147
+ domain: error.ErrorDomain.STORAGE,
6148
+ category: error.ErrorCategory.THIRD_PARTY,
6149
+ details: { mcpServerId: mcpServer.id }
6150
+ },
6151
+ error$1
6152
+ );
6153
+ }
6154
+ }
6155
+ async update(input) {
6156
+ const { id, ...updates } = input;
6157
+ try {
6158
+ const tableName = getTableName2({ indexName: storage.TABLE_MCP_SERVERS, schemaName: getSchemaName2(this.#schema) });
6159
+ const existingServer = await this.getById(id);
6160
+ if (!existingServer) {
6161
+ throw new error.MastraError({
6162
+ id: storage.createStorageErrorId("PG", "UPDATE_MCP_SERVER", "NOT_FOUND"),
6163
+ domain: error.ErrorDomain.STORAGE,
6164
+ category: error.ErrorCategory.USER,
6165
+ text: `MCP server ${id} not found`,
6166
+ details: { mcpServerId: id }
6167
+ });
6168
+ }
6169
+ const { authorId, activeVersionId, metadata, status } = updates;
6170
+ const setClauses = [];
6171
+ const values = [];
6172
+ let paramIndex = 1;
6173
+ if (authorId !== void 0) {
6174
+ setClauses.push(`"authorId" = $${paramIndex++}`);
6175
+ values.push(authorId);
6176
+ }
6177
+ if (activeVersionId !== void 0) {
6178
+ setClauses.push(`"activeVersionId" = $${paramIndex++}`);
6179
+ values.push(activeVersionId);
6180
+ }
6181
+ if (status !== void 0) {
6182
+ setClauses.push(`status = $${paramIndex++}`);
6183
+ values.push(status);
6184
+ }
6185
+ if (metadata !== void 0) {
6186
+ const mergedMetadata = { ...existingServer.metadata || {}, ...metadata };
6187
+ setClauses.push(`metadata = $${paramIndex++}`);
6188
+ values.push(JSON.stringify(mergedMetadata));
6189
+ }
6190
+ const now = (/* @__PURE__ */ new Date()).toISOString();
6191
+ setClauses.push(`"updatedAt" = $${paramIndex++}`);
6192
+ values.push(now);
6193
+ setClauses.push(`"updatedAtZ" = $${paramIndex++}`);
6194
+ values.push(now);
6195
+ values.push(id);
6196
+ await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
6197
+ const updatedServer = await this.getById(id);
6198
+ if (!updatedServer) {
6199
+ throw new error.MastraError({
6200
+ id: storage.createStorageErrorId("PG", "UPDATE_MCP_SERVER", "NOT_FOUND_AFTER_UPDATE"),
6201
+ domain: error.ErrorDomain.STORAGE,
6202
+ category: error.ErrorCategory.SYSTEM,
6203
+ text: `MCP server ${id} not found after update`,
6204
+ details: { mcpServerId: id }
6205
+ });
6206
+ }
6207
+ return updatedServer;
6208
+ } catch (error$1) {
6209
+ if (error$1 instanceof error.MastraError) throw error$1;
6210
+ throw new error.MastraError(
6211
+ {
6212
+ id: storage.createStorageErrorId("PG", "UPDATE_MCP_SERVER", "FAILED"),
6213
+ domain: error.ErrorDomain.STORAGE,
6214
+ category: error.ErrorCategory.THIRD_PARTY,
6215
+ details: { mcpServerId: id }
6216
+ },
6217
+ error$1
6218
+ );
6219
+ }
6220
+ }
6221
+ async delete(id) {
6222
+ try {
6223
+ const tableName = getTableName2({ indexName: storage.TABLE_MCP_SERVERS, schemaName: getSchemaName2(this.#schema) });
6224
+ await this.deleteVersionsByParentId(id);
6225
+ await this.#db.client.none(`DELETE FROM ${tableName} WHERE id = $1`, [id]);
6226
+ } catch (error$1) {
6227
+ if (error$1 instanceof error.MastraError) throw error$1;
6228
+ throw new error.MastraError(
6229
+ {
6230
+ id: storage.createStorageErrorId("PG", "DELETE_MCP_SERVER", "FAILED"),
6231
+ domain: error.ErrorDomain.STORAGE,
6232
+ category: error.ErrorCategory.THIRD_PARTY,
6233
+ details: { mcpServerId: id }
6234
+ },
6235
+ error$1
6236
+ );
6237
+ }
6238
+ }
6239
+ async list(args) {
6240
+ const { page = 0, perPage: perPageInput, orderBy, authorId, metadata, status = "published" } = args || {};
6241
+ const { field, direction } = this.parseOrderBy(orderBy);
6242
+ if (page < 0) {
6243
+ throw new error.MastraError(
6244
+ {
6245
+ id: storage.createStorageErrorId("PG", "LIST_MCP_SERVERS", "INVALID_PAGE"),
6246
+ domain: error.ErrorDomain.STORAGE,
6247
+ category: error.ErrorCategory.USER,
6248
+ details: { page }
6249
+ },
6250
+ new Error("page must be >= 0")
6251
+ );
6252
+ }
6253
+ const perPage = storage.normalizePerPage(perPageInput, 100);
6254
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
6255
+ try {
6256
+ const tableName = getTableName2({ indexName: storage.TABLE_MCP_SERVERS, schemaName: getSchemaName2(this.#schema) });
6257
+ const conditions = [];
6258
+ const queryParams = [];
6259
+ let paramIdx = 1;
6260
+ conditions.push(`status = $${paramIdx++}`);
6261
+ queryParams.push(status);
6262
+ if (authorId !== void 0) {
6263
+ conditions.push(`"authorId" = $${paramIdx++}`);
6264
+ queryParams.push(authorId);
6265
+ }
6266
+ if (metadata && Object.keys(metadata).length > 0) {
6267
+ conditions.push(`metadata @> $${paramIdx++}::jsonb`);
6268
+ queryParams.push(JSON.stringify(metadata));
6269
+ }
6270
+ const whereClause = `WHERE ${conditions.join(" AND ")}`;
6271
+ const countResult = await this.#db.client.one(
6272
+ `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`,
6273
+ queryParams
6274
+ );
6275
+ const total = parseInt(countResult.count, 10);
6276
+ if (total === 0) {
6277
+ return {
6278
+ mcpServers: [],
6279
+ total: 0,
6280
+ page,
6281
+ perPage: perPageForResponse,
6282
+ hasMore: false
6283
+ };
6284
+ }
6285
+ const limitValue = perPageInput === false ? total : perPage;
6286
+ const dataResult = await this.#db.client.manyOrNone(
6287
+ `SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`,
6288
+ [...queryParams, limitValue, offset]
6289
+ );
6290
+ const mcpServers = (dataResult || []).map((row) => this.parseMCPServerRow(row));
6291
+ return {
6292
+ mcpServers,
6293
+ total,
6294
+ page,
6295
+ perPage: perPageForResponse,
6296
+ hasMore: perPageInput === false ? false : offset + perPage < total
6297
+ };
6298
+ } catch (error$1) {
6299
+ if (error$1 instanceof error.MastraError) throw error$1;
6300
+ throw new error.MastraError(
6301
+ {
6302
+ id: storage.createStorageErrorId("PG", "LIST_MCP_SERVERS", "FAILED"),
6303
+ domain: error.ErrorDomain.STORAGE,
6304
+ category: error.ErrorCategory.THIRD_PARTY
6305
+ },
6306
+ error$1
6307
+ );
6308
+ }
6309
+ }
6310
+ // ==========================================================================
6311
+ // MCP Server Version Methods
6312
+ // ==========================================================================
6313
+ async createVersion(input) {
6314
+ try {
6315
+ const tableName = getTableName2({
6316
+ indexName: storage.TABLE_MCP_SERVER_VERSIONS,
6317
+ schemaName: getSchemaName2(this.#schema)
6318
+ });
6319
+ const now = /* @__PURE__ */ new Date();
6320
+ const nowIso = now.toISOString();
6321
+ await this.#db.client.none(
6322
+ `INSERT INTO ${tableName} (
6323
+ id, "mcpServerId", "versionNumber",
6324
+ name, version, description, instructions,
6325
+ repository, "releaseDate", "isLatest", "packageCanonical",
6326
+ tools, agents, workflows,
6327
+ "changedFields", "changeMessage",
6328
+ "createdAt", "createdAtZ"
6329
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)`,
6330
+ [
6331
+ input.id,
6332
+ input.mcpServerId,
6333
+ input.versionNumber,
6334
+ input.name,
6335
+ input.version,
6336
+ input.description ?? null,
6337
+ input.instructions ?? null,
6338
+ input.repository ? JSON.stringify(input.repository) : null,
6339
+ input.releaseDate ?? null,
6340
+ input.isLatest ?? null,
6341
+ input.packageCanonical ?? null,
6342
+ input.tools ? JSON.stringify(input.tools) : null,
6343
+ input.agents ? JSON.stringify(input.agents) : null,
6344
+ input.workflows ? JSON.stringify(input.workflows) : null,
6345
+ input.changedFields ? JSON.stringify(input.changedFields) : null,
6346
+ input.changeMessage ?? null,
6347
+ nowIso,
6348
+ nowIso
6349
+ ]
6350
+ );
6351
+ return {
6352
+ ...input,
6353
+ createdAt: now
6354
+ };
6355
+ } catch (error$1) {
6356
+ if (error$1 instanceof error.MastraError) throw error$1;
6357
+ throw new error.MastraError(
6358
+ {
6359
+ id: storage.createStorageErrorId("PG", "CREATE_MCP_SERVER_VERSION", "FAILED"),
6360
+ domain: error.ErrorDomain.STORAGE,
6361
+ category: error.ErrorCategory.THIRD_PARTY,
6362
+ details: { versionId: input.id, mcpServerId: input.mcpServerId }
6363
+ },
6364
+ error$1
6365
+ );
6366
+ }
6367
+ }
6368
+ async getVersion(id) {
6369
+ try {
6370
+ const tableName = getTableName2({
6371
+ indexName: storage.TABLE_MCP_SERVER_VERSIONS,
6372
+ schemaName: getSchemaName2(this.#schema)
6373
+ });
6374
+ const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
6375
+ if (!result) {
6376
+ return null;
6377
+ }
6378
+ return this.parseVersionRow(result);
6379
+ } catch (error$1) {
6380
+ if (error$1 instanceof error.MastraError) throw error$1;
6381
+ throw new error.MastraError(
6382
+ {
6383
+ id: storage.createStorageErrorId("PG", "GET_MCP_SERVER_VERSION", "FAILED"),
6384
+ domain: error.ErrorDomain.STORAGE,
6385
+ category: error.ErrorCategory.THIRD_PARTY,
6386
+ details: { versionId: id }
6387
+ },
6388
+ error$1
6389
+ );
6390
+ }
6391
+ }
6392
+ async getVersionByNumber(mcpServerId, versionNumber) {
6393
+ try {
6394
+ const tableName = getTableName2({
6395
+ indexName: storage.TABLE_MCP_SERVER_VERSIONS,
6396
+ schemaName: getSchemaName2(this.#schema)
6397
+ });
6398
+ const result = await this.#db.client.oneOrNone(
6399
+ `SELECT * FROM ${tableName} WHERE "mcpServerId" = $1 AND "versionNumber" = $2`,
6400
+ [mcpServerId, versionNumber]
6401
+ );
6402
+ if (!result) {
6403
+ return null;
6404
+ }
6405
+ return this.parseVersionRow(result);
6406
+ } catch (error$1) {
6407
+ if (error$1 instanceof error.MastraError) throw error$1;
6408
+ throw new error.MastraError(
6409
+ {
6410
+ id: storage.createStorageErrorId("PG", "GET_MCP_SERVER_VERSION_BY_NUMBER", "FAILED"),
6411
+ domain: error.ErrorDomain.STORAGE,
6412
+ category: error.ErrorCategory.THIRD_PARTY,
6413
+ details: { mcpServerId, versionNumber }
6414
+ },
6415
+ error$1
6416
+ );
6417
+ }
6418
+ }
6419
+ async getLatestVersion(mcpServerId) {
6420
+ try {
6421
+ const tableName = getTableName2({
6422
+ indexName: storage.TABLE_MCP_SERVER_VERSIONS,
6423
+ schemaName: getSchemaName2(this.#schema)
6424
+ });
6425
+ const result = await this.#db.client.oneOrNone(
6426
+ `SELECT * FROM ${tableName} WHERE "mcpServerId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`,
6427
+ [mcpServerId]
6428
+ );
6429
+ if (!result) {
6430
+ return null;
6431
+ }
6432
+ return this.parseVersionRow(result);
6433
+ } catch (error$1) {
6434
+ if (error$1 instanceof error.MastraError) throw error$1;
6435
+ throw new error.MastraError(
6436
+ {
6437
+ id: storage.createStorageErrorId("PG", "GET_LATEST_MCP_SERVER_VERSION", "FAILED"),
6438
+ domain: error.ErrorDomain.STORAGE,
6439
+ category: error.ErrorCategory.THIRD_PARTY,
6440
+ details: { mcpServerId }
6441
+ },
6442
+ error$1
6443
+ );
6444
+ }
6445
+ }
6446
+ async listVersions(input) {
6447
+ const { mcpServerId, page = 0, perPage: perPageInput, orderBy } = input;
6448
+ if (page < 0) {
6449
+ throw new error.MastraError(
6450
+ {
6451
+ id: storage.createStorageErrorId("PG", "LIST_MCP_SERVER_VERSIONS", "INVALID_PAGE"),
6452
+ domain: error.ErrorDomain.STORAGE,
6453
+ category: error.ErrorCategory.USER,
6454
+ details: { page }
6455
+ },
6456
+ new Error("page must be >= 0")
6457
+ );
6458
+ }
6459
+ const perPage = storage.normalizePerPage(perPageInput, 20);
6460
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
6461
+ try {
6462
+ const { field, direction } = this.parseVersionOrderBy(orderBy);
6463
+ const tableName = getTableName2({
6464
+ indexName: storage.TABLE_MCP_SERVER_VERSIONS,
6465
+ schemaName: getSchemaName2(this.#schema)
6466
+ });
6467
+ const countResult = await this.#db.client.one(
6468
+ `SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpServerId" = $1`,
6469
+ [mcpServerId]
6470
+ );
6471
+ const total = parseInt(countResult.count, 10);
6472
+ if (total === 0) {
6473
+ return {
6474
+ versions: [],
6475
+ total: 0,
6476
+ page,
6477
+ perPage: perPageForResponse,
6478
+ hasMore: false
6479
+ };
6480
+ }
6481
+ const limitValue = perPageInput === false ? total : perPage;
6482
+ const dataResult = await this.#db.client.manyOrNone(
6483
+ `SELECT * FROM ${tableName} WHERE "mcpServerId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`,
6484
+ [mcpServerId, limitValue, offset]
6485
+ );
6486
+ const versions = (dataResult || []).map((row) => this.parseVersionRow(row));
6487
+ return {
6488
+ versions,
6489
+ total,
6490
+ page,
6491
+ perPage: perPageForResponse,
6492
+ hasMore: perPageInput === false ? false : offset + perPage < total
6493
+ };
6494
+ } catch (error$1) {
6495
+ if (error$1 instanceof error.MastraError) throw error$1;
6496
+ throw new error.MastraError(
6497
+ {
6498
+ id: storage.createStorageErrorId("PG", "LIST_MCP_SERVER_VERSIONS", "FAILED"),
6499
+ domain: error.ErrorDomain.STORAGE,
6500
+ category: error.ErrorCategory.THIRD_PARTY,
6501
+ details: { mcpServerId }
6502
+ },
6503
+ error$1
6504
+ );
6505
+ }
6506
+ }
6507
+ async deleteVersion(id) {
6508
+ try {
6509
+ const tableName = getTableName2({
6510
+ indexName: storage.TABLE_MCP_SERVER_VERSIONS,
6511
+ schemaName: getSchemaName2(this.#schema)
6512
+ });
6513
+ await this.#db.client.none(`DELETE FROM ${tableName} WHERE id = $1`, [id]);
6514
+ } catch (error$1) {
6515
+ if (error$1 instanceof error.MastraError) throw error$1;
6516
+ throw new error.MastraError(
6517
+ {
6518
+ id: storage.createStorageErrorId("PG", "DELETE_MCP_SERVER_VERSION", "FAILED"),
6519
+ domain: error.ErrorDomain.STORAGE,
6520
+ category: error.ErrorCategory.THIRD_PARTY,
6521
+ details: { versionId: id }
6522
+ },
6523
+ error$1
6524
+ );
6525
+ }
6526
+ }
6527
+ async deleteVersionsByParentId(entityId) {
6528
+ try {
6529
+ const tableName = getTableName2({
6530
+ indexName: storage.TABLE_MCP_SERVER_VERSIONS,
6531
+ schemaName: getSchemaName2(this.#schema)
6532
+ });
6533
+ await this.#db.client.none(`DELETE FROM ${tableName} WHERE "mcpServerId" = $1`, [entityId]);
6534
+ } catch (error$1) {
6535
+ if (error$1 instanceof error.MastraError) throw error$1;
6536
+ throw new error.MastraError(
6537
+ {
6538
+ id: storage.createStorageErrorId("PG", "DELETE_MCP_SERVER_VERSIONS_BY_MCP_SERVER_ID", "FAILED"),
6539
+ domain: error.ErrorDomain.STORAGE,
6540
+ category: error.ErrorCategory.THIRD_PARTY,
6541
+ details: { mcpServerId: entityId }
6542
+ },
6543
+ error$1
6544
+ );
6545
+ }
6546
+ }
6547
+ async countVersions(mcpServerId) {
6548
+ try {
6549
+ const tableName = getTableName2({
6550
+ indexName: storage.TABLE_MCP_SERVER_VERSIONS,
6551
+ schemaName: getSchemaName2(this.#schema)
6552
+ });
6553
+ const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpServerId" = $1`, [
6554
+ mcpServerId
6555
+ ]);
6556
+ return parseInt(result.count, 10);
6557
+ } catch (error$1) {
6558
+ if (error$1 instanceof error.MastraError) throw error$1;
6559
+ throw new error.MastraError(
6560
+ {
6561
+ id: storage.createStorageErrorId("PG", "COUNT_MCP_SERVER_VERSIONS", "FAILED"),
6562
+ domain: error.ErrorDomain.STORAGE,
6563
+ category: error.ErrorCategory.THIRD_PARTY,
6564
+ details: { mcpServerId }
6565
+ },
6566
+ error$1
6567
+ );
6568
+ }
6569
+ }
6570
+ // ==========================================================================
6571
+ // Private Helper Methods
6572
+ // ==========================================================================
6573
+ parseJson(value, fieldName) {
6574
+ if (!value) return void 0;
6575
+ if (typeof value !== "string") return value;
6576
+ try {
6577
+ return JSON.parse(value);
6578
+ } catch (error$1) {
6579
+ if (error$1 instanceof error.MastraError) throw error$1;
6580
+ const details = {
6581
+ valueLength: String(value.length)
6582
+ };
6583
+ if (fieldName) {
6584
+ details.field = fieldName;
6585
+ }
6586
+ throw new error.MastraError(
6587
+ {
6588
+ id: storage.createStorageErrorId("PG", "PARSE_JSON", "INVALID_JSON"),
6589
+ domain: error.ErrorDomain.STORAGE,
6590
+ category: error.ErrorCategory.SYSTEM,
6591
+ text: `Failed to parse JSON${fieldName ? ` for field "${fieldName}"` : ""}: ${error$1 instanceof Error ? error$1.message : "Unknown error"}`,
6592
+ details
6593
+ },
6594
+ error$1
6595
+ );
6596
+ }
6597
+ }
6598
+ parseMCPServerRow(row) {
6599
+ return {
6600
+ id: row.id,
6601
+ status: row.status,
6602
+ activeVersionId: row.activeVersionId,
6603
+ authorId: row.authorId,
6604
+ metadata: this.parseJson(row.metadata, "metadata"),
6605
+ createdAt: new Date(row.createdAtZ || row.createdAt),
6606
+ updatedAt: new Date(row.updatedAtZ || row.updatedAt)
6607
+ };
6608
+ }
6609
+ parseVersionRow(row) {
6610
+ return {
6611
+ id: row.id,
6612
+ mcpServerId: row.mcpServerId,
6613
+ versionNumber: row.versionNumber,
6614
+ name: row.name,
6615
+ version: row.version,
6616
+ description: row.description,
6617
+ instructions: row.instructions,
6618
+ repository: this.parseJson(row.repository, "repository"),
6619
+ releaseDate: row.releaseDate,
6620
+ isLatest: row.isLatest,
6621
+ packageCanonical: row.packageCanonical,
6622
+ tools: this.parseJson(row.tools, "tools"),
6623
+ agents: this.parseJson(row.agents, "agents"),
6624
+ workflows: this.parseJson(row.workflows, "workflows"),
6625
+ changedFields: this.parseJson(row.changedFields, "changedFields"),
6626
+ changeMessage: row.changeMessage,
6627
+ createdAt: new Date(row.createdAtZ || row.createdAt)
6628
+ };
6629
+ }
6630
+ };
5989
6631
  var OM_TABLE = "mastra_observational_memory";
5990
6632
  var _omTableSchema;
5991
6633
  try {
@@ -7930,32 +8572,39 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
7930
8572
  const targetMessageTokens = Math.max(0, input.currentPendingTokens - retentionFloor);
7931
8573
  let cumulativeMessageTokens = 0;
7932
8574
  let chunksToActivate = 0;
7933
- let bestBoundary = 0;
7934
- let bestBoundaryMessageTokens = 0;
8575
+ let bestOverBoundary = 0;
8576
+ let bestOverTokens = 0;
8577
+ let bestUnderBoundary = 0;
8578
+ let bestUnderTokens = 0;
7935
8579
  for (let i = 0; i < chunks.length; i++) {
7936
8580
  cumulativeMessageTokens += chunks[i].messageTokens ?? 0;
7937
8581
  const boundary = i + 1;
7938
- const isUnder = cumulativeMessageTokens <= targetMessageTokens;
7939
- const bestIsUnder = bestBoundaryMessageTokens <= targetMessageTokens;
7940
- if (bestBoundary === 0) {
7941
- bestBoundary = boundary;
7942
- bestBoundaryMessageTokens = cumulativeMessageTokens;
7943
- } else if (isUnder && !bestIsUnder) {
7944
- bestBoundary = boundary;
7945
- bestBoundaryMessageTokens = cumulativeMessageTokens;
7946
- } else if (isUnder && bestIsUnder) {
7947
- if (cumulativeMessageTokens > bestBoundaryMessageTokens) {
7948
- bestBoundary = boundary;
7949
- bestBoundaryMessageTokens = cumulativeMessageTokens;
8582
+ if (cumulativeMessageTokens >= targetMessageTokens) {
8583
+ if (bestOverBoundary === 0 || cumulativeMessageTokens < bestOverTokens) {
8584
+ bestOverBoundary = boundary;
8585
+ bestOverTokens = cumulativeMessageTokens;
7950
8586
  }
7951
- } else if (!isUnder && !bestIsUnder) {
7952
- if (cumulativeMessageTokens < bestBoundaryMessageTokens) {
7953
- bestBoundary = boundary;
7954
- bestBoundaryMessageTokens = cumulativeMessageTokens;
8587
+ } else {
8588
+ if (cumulativeMessageTokens > bestUnderTokens) {
8589
+ bestUnderBoundary = boundary;
8590
+ bestUnderTokens = cumulativeMessageTokens;
7955
8591
  }
7956
8592
  }
7957
8593
  }
7958
- chunksToActivate = bestBoundary === 0 ? 1 : bestBoundary;
8594
+ const maxOvershoot = retentionFloor * 0.95;
8595
+ const overshoot = bestOverTokens - targetMessageTokens;
8596
+ const remainingAfterOver = input.currentPendingTokens - bestOverTokens;
8597
+ if (input.forceMaxActivation && bestOverBoundary > 0) {
8598
+ chunksToActivate = bestOverBoundary;
8599
+ } else if (bestOverBoundary > 0 && overshoot <= maxOvershoot && (remainingAfterOver >= 1e3 || retentionFloor === 0)) {
8600
+ chunksToActivate = bestOverBoundary;
8601
+ } else if (bestUnderBoundary > 0) {
8602
+ chunksToActivate = bestUnderBoundary;
8603
+ } else if (bestOverBoundary > 0) {
8604
+ chunksToActivate = bestOverBoundary;
8605
+ } else {
8606
+ chunksToActivate = 1;
8607
+ }
7959
8608
  const activatedChunks = chunks.slice(0, chunksToActivate);
7960
8609
  const remainingChunks = chunks.slice(chunksToActivate);
7961
8610
  const activatedContent = activatedChunks.map((c) => c.observations).join("\n\n");
@@ -7994,6 +8643,7 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
7994
8643
  input.id
7995
8644
  ]
7996
8645
  );
8646
+ const latestChunkHints = activatedChunks[activatedChunks.length - 1];
7997
8647
  return {
7998
8648
  chunksActivated: activatedChunks.length,
7999
8649
  messageTokensActivated: activatedMessageTokens,
@@ -8008,7 +8658,9 @@ var MemoryPG = class _MemoryPG extends storage.MemoryStorage {
8008
8658
  observationTokens: c.tokenCount,
8009
8659
  messageCount: c.messageIds.length,
8010
8660
  observations: c.observations
8011
- }))
8661
+ })),
8662
+ suggestedContinuation: latestChunkHints?.suggestedContinuation ?? void 0,
8663
+ currentTask: latestChunkHints?.currentTask ?? void 0
8012
8664
  };
8013
8665
  } catch (error$1) {
8014
8666
  if (error$1 instanceof error.MastraError) {
@@ -8792,7 +9444,7 @@ var ObservabilityPG = class _ObservabilityPG extends storage.ObservabilityStorag
8792
9444
  }
8793
9445
  }
8794
9446
  };
8795
- var SNAPSHOT_FIELDS2 = ["name", "description", "content", "rules"];
9447
+ var SNAPSHOT_FIELDS3 = ["name", "description", "content", "rules"];
8796
9448
  var PromptBlocksPG = class _PromptBlocksPG extends storage.PromptBlocksStorage {
8797
9449
  #db;
8798
9450
  #schema;
@@ -8938,7 +9590,7 @@ var PromptBlocksPG = class _PromptBlocksPG extends storage.PromptBlocksStorage {
8938
9590
  blockId: promptBlock.id,
8939
9591
  versionNumber: 1,
8940
9592
  ...snapshotConfig,
8941
- changedFields: [...SNAPSHOT_FIELDS2],
9593
+ changedFields: [...SNAPSHOT_FIELDS3],
8942
9594
  changeMessage: "Initial version"
8943
9595
  });
8944
9596
  return {
@@ -9429,7 +10081,7 @@ var PromptBlocksPG = class _PromptBlocksPG extends storage.PromptBlocksStorage {
9429
10081
  };
9430
10082
  }
9431
10083
  };
9432
- var SNAPSHOT_FIELDS3 = [
10084
+ var SNAPSHOT_FIELDS4 = [
9433
10085
  "name",
9434
10086
  "description",
9435
10087
  "type",
@@ -9589,7 +10241,7 @@ var ScorerDefinitionsPG = class _ScorerDefinitionsPG extends storage.ScorerDefin
9589
10241
  scorerDefinitionId: scorerDefinition.id,
9590
10242
  versionNumber: 1,
9591
10243
  ...snapshotConfig,
9592
- changedFields: [...SNAPSHOT_FIELDS3],
10244
+ changedFields: [...SNAPSHOT_FIELDS4],
9593
10245
  changeMessage: "Initial version"
9594
10246
  });
9595
10247
  return {
@@ -10505,7 +11157,7 @@ var ScoresPG = class _ScoresPG extends storage.ScoresStorage {
10505
11157
  }
10506
11158
  }
10507
11159
  };
10508
- var SNAPSHOT_FIELDS4 = [
11160
+ var SNAPSHOT_FIELDS5 = [
10509
11161
  "name",
10510
11162
  "description",
10511
11163
  "instructions",
@@ -10625,7 +11277,7 @@ var SkillsPG = class _SkillsPG extends storage.SkillsStorage {
10625
11277
  skillId: skill.id,
10626
11278
  versionNumber: 1,
10627
11279
  ...snapshotConfig,
10628
- changedFields: [...SNAPSHOT_FIELDS4],
11280
+ changedFields: [...SNAPSHOT_FIELDS5],
10629
11281
  changeMessage: "Initial version"
10630
11282
  });
10631
11283
  return {
@@ -10676,7 +11328,7 @@ var SkillsPG = class _SkillsPG extends storage.SkillsStorage {
10676
11328
  }
10677
11329
  const { authorId, activeVersionId, status, ...configFields } = updates;
10678
11330
  let versionCreated = false;
10679
- const hasConfigUpdate = SNAPSHOT_FIELDS4.some((field) => field in configFields);
11331
+ const hasConfigUpdate = SNAPSHOT_FIELDS5.some((field) => field in configFields);
10680
11332
  if (hasConfigUpdate) {
10681
11333
  const latestVersion = await this.getLatestVersion(id);
10682
11334
  if (!latestVersion) {
@@ -10698,7 +11350,7 @@ var SkillsPG = class _SkillsPG extends storage.SkillsStorage {
10698
11350
  ...latestConfig
10699
11351
  } = latestVersion;
10700
11352
  const newConfig = { ...latestConfig, ...configFields };
10701
- const changedFields = SNAPSHOT_FIELDS4.filter(
11353
+ const changedFields = SNAPSHOT_FIELDS5.filter(
10702
11354
  (field) => field in configFields && JSON.stringify(configFields[field]) !== JSON.stringify(latestConfig[field])
10703
11355
  );
10704
11356
  if (changedFields.length > 0) {
@@ -11491,7 +12143,7 @@ var WorkflowsPG = class _WorkflowsPG extends storage.WorkflowsStorage {
11491
12143
  }
11492
12144
  }
11493
12145
  };
11494
- var SNAPSHOT_FIELDS5 = [
12146
+ var SNAPSHOT_FIELDS6 = [
11495
12147
  "name",
11496
12148
  "description",
11497
12149
  "filesystem",
@@ -11620,7 +12272,7 @@ var WorkspacesPG = class _WorkspacesPG extends storage.WorkspacesStorage {
11620
12272
  workspaceId: workspace.id,
11621
12273
  versionNumber: 1,
11622
12274
  ...snapshotConfig,
11623
- changedFields: [...SNAPSHOT_FIELDS5],
12275
+ changedFields: [...SNAPSHOT_FIELDS6],
11624
12276
  changeMessage: "Initial version"
11625
12277
  });
11626
12278
  return {
@@ -11672,7 +12324,7 @@ var WorkspacesPG = class _WorkspacesPG extends storage.WorkspacesStorage {
11672
12324
  }
11673
12325
  const { authorId, activeVersionId, metadata, status, ...configFields } = updates;
11674
12326
  let versionCreated = false;
11675
- const hasConfigUpdate = SNAPSHOT_FIELDS5.some((field) => field in configFields);
12327
+ const hasConfigUpdate = SNAPSHOT_FIELDS6.some((field) => field in configFields);
11676
12328
  if (hasConfigUpdate) {
11677
12329
  const latestVersion = await this.getLatestVersion(id);
11678
12330
  if (!latestVersion) {
@@ -11694,7 +12346,7 @@ var WorkspacesPG = class _WorkspacesPG extends storage.WorkspacesStorage {
11694
12346
  ...latestConfig
11695
12347
  } = latestVersion;
11696
12348
  const newConfig = { ...latestConfig, ...configFields };
11697
- const changedFields = SNAPSHOT_FIELDS5.filter(
12349
+ const changedFields = SNAPSHOT_FIELDS6.filter(
11698
12350
  (field) => field in configFields && JSON.stringify(configFields[field]) !== JSON.stringify(latestConfig[field])
11699
12351
  );
11700
12352
  if (changedFields.length > 0) {
@@ -12237,6 +12889,7 @@ var PostgresStore = class extends storage.MastraCompositeStore {
12237
12889
  promptBlocks: new PromptBlocksPG(domainConfig),
12238
12890
  scorerDefinitions: new ScorerDefinitionsPG(domainConfig),
12239
12891
  mcpClients: new MCPClientsPG(domainConfig),
12892
+ mcpServers: new MCPServersPG(domainConfig),
12240
12893
  workspaces: new WorkspacesPG(domainConfig),
12241
12894
  skills: new SkillsPG(domainConfig),
12242
12895
  blobs: new BlobsPG(domainConfig),
@@ -12435,6 +13088,7 @@ exports.BlobsPG = BlobsPG;
12435
13088
  exports.DatasetsPG = DatasetsPG;
12436
13089
  exports.ExperimentsPG = ExperimentsPG;
12437
13090
  exports.MCPClientsPG = MCPClientsPG;
13091
+ exports.MCPServersPG = MCPServersPG;
12438
13092
  exports.MemoryPG = MemoryPG;
12439
13093
  exports.ObservabilityPG = ObservabilityPG;
12440
13094
  exports.PGVECTOR_PROMPT = PGVECTOR_PROMPT;