@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.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, TABLE_SCHEMAS, createStorageErrorId, normalizePerPage, calculatePagination, BlobStore, TABLE_SKILL_BLOBS, DatasetsStorage, TABLE_DATASETS, TABLE_DATASET_ITEMS, TABLE_DATASET_VERSIONS, DATASETS_SCHEMA, TABLE_CONFIGS, DATASET_ITEMS_SCHEMA, DATASET_VERSIONS_SCHEMA, ensureDate, safelyParseJSON, ExperimentsStorage, TABLE_EXPERIMENTS, TABLE_EXPERIMENT_RESULTS, EXPERIMENTS_SCHEMA, EXPERIMENT_RESULTS_SCHEMA, MCPClientsStorage, TABLE_MCP_CLIENTS, TABLE_MCP_CLIENT_VERSIONS, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, 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, getDefaultValue, transformScoreRow as transformScoreRow$1, getSqlType } from '@mastra/core/storage';
2
+ import { createVectorErrorId, AgentsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, TABLE_SCHEMAS, createStorageErrorId, normalizePerPage, calculatePagination, BlobStore, TABLE_SKILL_BLOBS, DatasetsStorage, TABLE_DATASETS, TABLE_DATASET_ITEMS, TABLE_DATASET_VERSIONS, DATASETS_SCHEMA, TABLE_CONFIGS, DATASET_ITEMS_SCHEMA, DATASET_VERSIONS_SCHEMA, ensureDate, safelyParseJSON, ExperimentsStorage, TABLE_EXPERIMENTS, TABLE_EXPERIMENT_RESULTS, EXPERIMENTS_SCHEMA, EXPERIMENT_RESULTS_SCHEMA, MCPClientsStorage, TABLE_MCP_CLIENTS, TABLE_MCP_CLIENT_VERSIONS, MCPServersStorage, TABLE_MCP_SERVERS, TABLE_MCP_SERVER_VERSIONS, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, 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, getDefaultValue, transformScoreRow as transformScoreRow$1, getSqlType } from '@mastra/core/storage';
3
3
  import { parseSqlIdentifier, parseFieldKey } from '@mastra/core/utils';
4
4
  import { MastraVector, validateTopK, validateUpsertInput } from '@mastra/core/vector';
5
5
  import { Mutex } from 'async-mutex';
@@ -5962,6 +5962,648 @@ var MCPClientsPG = class _MCPClientsPG extends MCPClientsStorage {
5962
5962
  };
5963
5963
  }
5964
5964
  };
5965
+ var SNAPSHOT_FIELDS2 = [
5966
+ "name",
5967
+ "version",
5968
+ "description",
5969
+ "instructions",
5970
+ "repository",
5971
+ "releaseDate",
5972
+ "isLatest",
5973
+ "packageCanonical",
5974
+ "tools",
5975
+ "agents",
5976
+ "workflows"
5977
+ ];
5978
+ var MCPServersPG = class _MCPServersPG extends MCPServersStorage {
5979
+ #db;
5980
+ #schema;
5981
+ #skipDefaultIndexes;
5982
+ #indexes;
5983
+ static MANAGED_TABLES = [TABLE_MCP_SERVERS, TABLE_MCP_SERVER_VERSIONS];
5984
+ constructor(config) {
5985
+ super();
5986
+ const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
5987
+ this.#db = new PgDB({ client, schemaName, skipDefaultIndexes });
5988
+ this.#schema = schemaName || "public";
5989
+ this.#skipDefaultIndexes = skipDefaultIndexes;
5990
+ this.#indexes = indexes?.filter((idx) => _MCPServersPG.MANAGED_TABLES.includes(idx.table));
5991
+ }
5992
+ getDefaultIndexDefinitions() {
5993
+ return [
5994
+ {
5995
+ name: "idx_mcp_server_versions_server_version",
5996
+ table: TABLE_MCP_SERVER_VERSIONS,
5997
+ columns: ["mcpServerId", "versionNumber"],
5998
+ unique: true
5999
+ }
6000
+ ];
6001
+ }
6002
+ async createDefaultIndexes() {
6003
+ if (this.#skipDefaultIndexes) {
6004
+ return;
6005
+ }
6006
+ for (const indexDef of this.getDefaultIndexDefinitions()) {
6007
+ try {
6008
+ await this.#db.createIndex(indexDef);
6009
+ } catch {
6010
+ }
6011
+ }
6012
+ }
6013
+ async init() {
6014
+ await this.#db.createTable({
6015
+ tableName: TABLE_MCP_SERVERS,
6016
+ schema: TABLE_SCHEMAS[TABLE_MCP_SERVERS]
6017
+ });
6018
+ await this.#db.createTable({
6019
+ tableName: TABLE_MCP_SERVER_VERSIONS,
6020
+ schema: TABLE_SCHEMAS[TABLE_MCP_SERVER_VERSIONS]
6021
+ });
6022
+ await this.createDefaultIndexes();
6023
+ await this.createCustomIndexes();
6024
+ }
6025
+ async createCustomIndexes() {
6026
+ if (!this.#indexes || this.#indexes.length === 0) {
6027
+ return;
6028
+ }
6029
+ for (const indexDef of this.#indexes) {
6030
+ try {
6031
+ await this.#db.createIndex(indexDef);
6032
+ } catch (error) {
6033
+ this.logger?.warn?.(`Failed to create custom index ${indexDef.name}:`, error);
6034
+ }
6035
+ }
6036
+ }
6037
+ async dangerouslyClearAll() {
6038
+ await this.#db.clearTable({ tableName: TABLE_MCP_SERVER_VERSIONS });
6039
+ await this.#db.clearTable({ tableName: TABLE_MCP_SERVERS });
6040
+ }
6041
+ // ==========================================================================
6042
+ // MCP Server CRUD Methods
6043
+ // ==========================================================================
6044
+ async getById(id) {
6045
+ try {
6046
+ const tableName = getTableName2({ indexName: TABLE_MCP_SERVERS, schemaName: getSchemaName2(this.#schema) });
6047
+ const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
6048
+ if (!result) {
6049
+ return null;
6050
+ }
6051
+ return this.parseMCPServerRow(result);
6052
+ } catch (error) {
6053
+ if (error instanceof MastraError) throw error;
6054
+ throw new MastraError(
6055
+ {
6056
+ id: createStorageErrorId("PG", "GET_MCP_SERVER_BY_ID", "FAILED"),
6057
+ domain: ErrorDomain.STORAGE,
6058
+ category: ErrorCategory.THIRD_PARTY,
6059
+ details: { mcpServerId: id }
6060
+ },
6061
+ error
6062
+ );
6063
+ }
6064
+ }
6065
+ async create(input) {
6066
+ const { mcpServer } = input;
6067
+ try {
6068
+ const tableName = getTableName2({ indexName: TABLE_MCP_SERVERS, schemaName: getSchemaName2(this.#schema) });
6069
+ const now = /* @__PURE__ */ new Date();
6070
+ const nowIso = now.toISOString();
6071
+ await this.#db.client.none(
6072
+ `INSERT INTO ${tableName} (
6073
+ id, status, "activeVersionId", "authorId", metadata,
6074
+ "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
6075
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
6076
+ [
6077
+ mcpServer.id,
6078
+ "draft",
6079
+ null,
6080
+ mcpServer.authorId ?? null,
6081
+ mcpServer.metadata ? JSON.stringify(mcpServer.metadata) : null,
6082
+ nowIso,
6083
+ nowIso,
6084
+ nowIso,
6085
+ nowIso
6086
+ ]
6087
+ );
6088
+ const { id: _id, authorId: _authorId, metadata: _metadata, ...snapshotConfig } = mcpServer;
6089
+ const versionId = crypto.randomUUID();
6090
+ await this.createVersion({
6091
+ id: versionId,
6092
+ mcpServerId: mcpServer.id,
6093
+ versionNumber: 1,
6094
+ ...snapshotConfig,
6095
+ changedFields: [...SNAPSHOT_FIELDS2],
6096
+ changeMessage: "Initial version"
6097
+ });
6098
+ return {
6099
+ id: mcpServer.id,
6100
+ status: "draft",
6101
+ activeVersionId: void 0,
6102
+ authorId: mcpServer.authorId,
6103
+ metadata: mcpServer.metadata,
6104
+ createdAt: now,
6105
+ updatedAt: now
6106
+ };
6107
+ } catch (error) {
6108
+ try {
6109
+ const tableName = getTableName2({
6110
+ indexName: TABLE_MCP_SERVERS,
6111
+ schemaName: getSchemaName2(this.#schema)
6112
+ });
6113
+ await this.#db.client.none(
6114
+ `DELETE FROM ${tableName} WHERE id = $1 AND status = 'draft' AND "activeVersionId" IS NULL`,
6115
+ [mcpServer.id]
6116
+ );
6117
+ } catch {
6118
+ }
6119
+ if (error instanceof MastraError) throw error;
6120
+ throw new MastraError(
6121
+ {
6122
+ id: createStorageErrorId("PG", "CREATE_MCP_SERVER", "FAILED"),
6123
+ domain: ErrorDomain.STORAGE,
6124
+ category: ErrorCategory.THIRD_PARTY,
6125
+ details: { mcpServerId: mcpServer.id }
6126
+ },
6127
+ error
6128
+ );
6129
+ }
6130
+ }
6131
+ async update(input) {
6132
+ const { id, ...updates } = input;
6133
+ try {
6134
+ const tableName = getTableName2({ indexName: TABLE_MCP_SERVERS, schemaName: getSchemaName2(this.#schema) });
6135
+ const existingServer = await this.getById(id);
6136
+ if (!existingServer) {
6137
+ throw new MastraError({
6138
+ id: createStorageErrorId("PG", "UPDATE_MCP_SERVER", "NOT_FOUND"),
6139
+ domain: ErrorDomain.STORAGE,
6140
+ category: ErrorCategory.USER,
6141
+ text: `MCP server ${id} not found`,
6142
+ details: { mcpServerId: id }
6143
+ });
6144
+ }
6145
+ const { authorId, activeVersionId, metadata, status } = updates;
6146
+ const setClauses = [];
6147
+ const values = [];
6148
+ let paramIndex = 1;
6149
+ if (authorId !== void 0) {
6150
+ setClauses.push(`"authorId" = $${paramIndex++}`);
6151
+ values.push(authorId);
6152
+ }
6153
+ if (activeVersionId !== void 0) {
6154
+ setClauses.push(`"activeVersionId" = $${paramIndex++}`);
6155
+ values.push(activeVersionId);
6156
+ }
6157
+ if (status !== void 0) {
6158
+ setClauses.push(`status = $${paramIndex++}`);
6159
+ values.push(status);
6160
+ }
6161
+ if (metadata !== void 0) {
6162
+ const mergedMetadata = { ...existingServer.metadata || {}, ...metadata };
6163
+ setClauses.push(`metadata = $${paramIndex++}`);
6164
+ values.push(JSON.stringify(mergedMetadata));
6165
+ }
6166
+ const now = (/* @__PURE__ */ new Date()).toISOString();
6167
+ setClauses.push(`"updatedAt" = $${paramIndex++}`);
6168
+ values.push(now);
6169
+ setClauses.push(`"updatedAtZ" = $${paramIndex++}`);
6170
+ values.push(now);
6171
+ values.push(id);
6172
+ await this.#db.client.none(`UPDATE ${tableName} SET ${setClauses.join(", ")} WHERE id = $${paramIndex}`, values);
6173
+ const updatedServer = await this.getById(id);
6174
+ if (!updatedServer) {
6175
+ throw new MastraError({
6176
+ id: createStorageErrorId("PG", "UPDATE_MCP_SERVER", "NOT_FOUND_AFTER_UPDATE"),
6177
+ domain: ErrorDomain.STORAGE,
6178
+ category: ErrorCategory.SYSTEM,
6179
+ text: `MCP server ${id} not found after update`,
6180
+ details: { mcpServerId: id }
6181
+ });
6182
+ }
6183
+ return updatedServer;
6184
+ } catch (error) {
6185
+ if (error instanceof MastraError) throw error;
6186
+ throw new MastraError(
6187
+ {
6188
+ id: createStorageErrorId("PG", "UPDATE_MCP_SERVER", "FAILED"),
6189
+ domain: ErrorDomain.STORAGE,
6190
+ category: ErrorCategory.THIRD_PARTY,
6191
+ details: { mcpServerId: id }
6192
+ },
6193
+ error
6194
+ );
6195
+ }
6196
+ }
6197
+ async delete(id) {
6198
+ try {
6199
+ const tableName = getTableName2({ indexName: TABLE_MCP_SERVERS, schemaName: getSchemaName2(this.#schema) });
6200
+ await this.deleteVersionsByParentId(id);
6201
+ await this.#db.client.none(`DELETE FROM ${tableName} WHERE id = $1`, [id]);
6202
+ } catch (error) {
6203
+ if (error instanceof MastraError) throw error;
6204
+ throw new MastraError(
6205
+ {
6206
+ id: createStorageErrorId("PG", "DELETE_MCP_SERVER", "FAILED"),
6207
+ domain: ErrorDomain.STORAGE,
6208
+ category: ErrorCategory.THIRD_PARTY,
6209
+ details: { mcpServerId: id }
6210
+ },
6211
+ error
6212
+ );
6213
+ }
6214
+ }
6215
+ async list(args) {
6216
+ const { page = 0, perPage: perPageInput, orderBy, authorId, metadata, status = "published" } = args || {};
6217
+ const { field, direction } = this.parseOrderBy(orderBy);
6218
+ if (page < 0) {
6219
+ throw new MastraError(
6220
+ {
6221
+ id: createStorageErrorId("PG", "LIST_MCP_SERVERS", "INVALID_PAGE"),
6222
+ domain: ErrorDomain.STORAGE,
6223
+ category: ErrorCategory.USER,
6224
+ details: { page }
6225
+ },
6226
+ new Error("page must be >= 0")
6227
+ );
6228
+ }
6229
+ const perPage = normalizePerPage(perPageInput, 100);
6230
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
6231
+ try {
6232
+ const tableName = getTableName2({ indexName: TABLE_MCP_SERVERS, schemaName: getSchemaName2(this.#schema) });
6233
+ const conditions = [];
6234
+ const queryParams = [];
6235
+ let paramIdx = 1;
6236
+ conditions.push(`status = $${paramIdx++}`);
6237
+ queryParams.push(status);
6238
+ if (authorId !== void 0) {
6239
+ conditions.push(`"authorId" = $${paramIdx++}`);
6240
+ queryParams.push(authorId);
6241
+ }
6242
+ if (metadata && Object.keys(metadata).length > 0) {
6243
+ conditions.push(`metadata @> $${paramIdx++}::jsonb`);
6244
+ queryParams.push(JSON.stringify(metadata));
6245
+ }
6246
+ const whereClause = `WHERE ${conditions.join(" AND ")}`;
6247
+ const countResult = await this.#db.client.one(
6248
+ `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`,
6249
+ queryParams
6250
+ );
6251
+ const total = parseInt(countResult.count, 10);
6252
+ if (total === 0) {
6253
+ return {
6254
+ mcpServers: [],
6255
+ total: 0,
6256
+ page,
6257
+ perPage: perPageForResponse,
6258
+ hasMore: false
6259
+ };
6260
+ }
6261
+ const limitValue = perPageInput === false ? total : perPage;
6262
+ const dataResult = await this.#db.client.manyOrNone(
6263
+ `SELECT * FROM ${tableName} ${whereClause} ORDER BY "${field}" ${direction} LIMIT $${paramIdx++} OFFSET $${paramIdx++}`,
6264
+ [...queryParams, limitValue, offset]
6265
+ );
6266
+ const mcpServers = (dataResult || []).map((row) => this.parseMCPServerRow(row));
6267
+ return {
6268
+ mcpServers,
6269
+ total,
6270
+ page,
6271
+ perPage: perPageForResponse,
6272
+ hasMore: perPageInput === false ? false : offset + perPage < total
6273
+ };
6274
+ } catch (error) {
6275
+ if (error instanceof MastraError) throw error;
6276
+ throw new MastraError(
6277
+ {
6278
+ id: createStorageErrorId("PG", "LIST_MCP_SERVERS", "FAILED"),
6279
+ domain: ErrorDomain.STORAGE,
6280
+ category: ErrorCategory.THIRD_PARTY
6281
+ },
6282
+ error
6283
+ );
6284
+ }
6285
+ }
6286
+ // ==========================================================================
6287
+ // MCP Server Version Methods
6288
+ // ==========================================================================
6289
+ async createVersion(input) {
6290
+ try {
6291
+ const tableName = getTableName2({
6292
+ indexName: TABLE_MCP_SERVER_VERSIONS,
6293
+ schemaName: getSchemaName2(this.#schema)
6294
+ });
6295
+ const now = /* @__PURE__ */ new Date();
6296
+ const nowIso = now.toISOString();
6297
+ await this.#db.client.none(
6298
+ `INSERT INTO ${tableName} (
6299
+ id, "mcpServerId", "versionNumber",
6300
+ name, version, description, instructions,
6301
+ repository, "releaseDate", "isLatest", "packageCanonical",
6302
+ tools, agents, workflows,
6303
+ "changedFields", "changeMessage",
6304
+ "createdAt", "createdAtZ"
6305
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)`,
6306
+ [
6307
+ input.id,
6308
+ input.mcpServerId,
6309
+ input.versionNumber,
6310
+ input.name,
6311
+ input.version,
6312
+ input.description ?? null,
6313
+ input.instructions ?? null,
6314
+ input.repository ? JSON.stringify(input.repository) : null,
6315
+ input.releaseDate ?? null,
6316
+ input.isLatest ?? null,
6317
+ input.packageCanonical ?? null,
6318
+ input.tools ? JSON.stringify(input.tools) : null,
6319
+ input.agents ? JSON.stringify(input.agents) : null,
6320
+ input.workflows ? JSON.stringify(input.workflows) : null,
6321
+ input.changedFields ? JSON.stringify(input.changedFields) : null,
6322
+ input.changeMessage ?? null,
6323
+ nowIso,
6324
+ nowIso
6325
+ ]
6326
+ );
6327
+ return {
6328
+ ...input,
6329
+ createdAt: now
6330
+ };
6331
+ } catch (error) {
6332
+ if (error instanceof MastraError) throw error;
6333
+ throw new MastraError(
6334
+ {
6335
+ id: createStorageErrorId("PG", "CREATE_MCP_SERVER_VERSION", "FAILED"),
6336
+ domain: ErrorDomain.STORAGE,
6337
+ category: ErrorCategory.THIRD_PARTY,
6338
+ details: { versionId: input.id, mcpServerId: input.mcpServerId }
6339
+ },
6340
+ error
6341
+ );
6342
+ }
6343
+ }
6344
+ async getVersion(id) {
6345
+ try {
6346
+ const tableName = getTableName2({
6347
+ indexName: TABLE_MCP_SERVER_VERSIONS,
6348
+ schemaName: getSchemaName2(this.#schema)
6349
+ });
6350
+ const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
6351
+ if (!result) {
6352
+ return null;
6353
+ }
6354
+ return this.parseVersionRow(result);
6355
+ } catch (error) {
6356
+ if (error instanceof MastraError) throw error;
6357
+ throw new MastraError(
6358
+ {
6359
+ id: createStorageErrorId("PG", "GET_MCP_SERVER_VERSION", "FAILED"),
6360
+ domain: ErrorDomain.STORAGE,
6361
+ category: ErrorCategory.THIRD_PARTY,
6362
+ details: { versionId: id }
6363
+ },
6364
+ error
6365
+ );
6366
+ }
6367
+ }
6368
+ async getVersionByNumber(mcpServerId, versionNumber) {
6369
+ try {
6370
+ const tableName = getTableName2({
6371
+ indexName: TABLE_MCP_SERVER_VERSIONS,
6372
+ schemaName: getSchemaName2(this.#schema)
6373
+ });
6374
+ const result = await this.#db.client.oneOrNone(
6375
+ `SELECT * FROM ${tableName} WHERE "mcpServerId" = $1 AND "versionNumber" = $2`,
6376
+ [mcpServerId, versionNumber]
6377
+ );
6378
+ if (!result) {
6379
+ return null;
6380
+ }
6381
+ return this.parseVersionRow(result);
6382
+ } catch (error) {
6383
+ if (error instanceof MastraError) throw error;
6384
+ throw new MastraError(
6385
+ {
6386
+ id: createStorageErrorId("PG", "GET_MCP_SERVER_VERSION_BY_NUMBER", "FAILED"),
6387
+ domain: ErrorDomain.STORAGE,
6388
+ category: ErrorCategory.THIRD_PARTY,
6389
+ details: { mcpServerId, versionNumber }
6390
+ },
6391
+ error
6392
+ );
6393
+ }
6394
+ }
6395
+ async getLatestVersion(mcpServerId) {
6396
+ try {
6397
+ const tableName = getTableName2({
6398
+ indexName: TABLE_MCP_SERVER_VERSIONS,
6399
+ schemaName: getSchemaName2(this.#schema)
6400
+ });
6401
+ const result = await this.#db.client.oneOrNone(
6402
+ `SELECT * FROM ${tableName} WHERE "mcpServerId" = $1 ORDER BY "versionNumber" DESC LIMIT 1`,
6403
+ [mcpServerId]
6404
+ );
6405
+ if (!result) {
6406
+ return null;
6407
+ }
6408
+ return this.parseVersionRow(result);
6409
+ } catch (error) {
6410
+ if (error instanceof MastraError) throw error;
6411
+ throw new MastraError(
6412
+ {
6413
+ id: createStorageErrorId("PG", "GET_LATEST_MCP_SERVER_VERSION", "FAILED"),
6414
+ domain: ErrorDomain.STORAGE,
6415
+ category: ErrorCategory.THIRD_PARTY,
6416
+ details: { mcpServerId }
6417
+ },
6418
+ error
6419
+ );
6420
+ }
6421
+ }
6422
+ async listVersions(input) {
6423
+ const { mcpServerId, page = 0, perPage: perPageInput, orderBy } = input;
6424
+ if (page < 0) {
6425
+ throw new MastraError(
6426
+ {
6427
+ id: createStorageErrorId("PG", "LIST_MCP_SERVER_VERSIONS", "INVALID_PAGE"),
6428
+ domain: ErrorDomain.STORAGE,
6429
+ category: ErrorCategory.USER,
6430
+ details: { page }
6431
+ },
6432
+ new Error("page must be >= 0")
6433
+ );
6434
+ }
6435
+ const perPage = normalizePerPage(perPageInput, 20);
6436
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
6437
+ try {
6438
+ const { field, direction } = this.parseVersionOrderBy(orderBy);
6439
+ const tableName = getTableName2({
6440
+ indexName: TABLE_MCP_SERVER_VERSIONS,
6441
+ schemaName: getSchemaName2(this.#schema)
6442
+ });
6443
+ const countResult = await this.#db.client.one(
6444
+ `SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpServerId" = $1`,
6445
+ [mcpServerId]
6446
+ );
6447
+ const total = parseInt(countResult.count, 10);
6448
+ if (total === 0) {
6449
+ return {
6450
+ versions: [],
6451
+ total: 0,
6452
+ page,
6453
+ perPage: perPageForResponse,
6454
+ hasMore: false
6455
+ };
6456
+ }
6457
+ const limitValue = perPageInput === false ? total : perPage;
6458
+ const dataResult = await this.#db.client.manyOrNone(
6459
+ `SELECT * FROM ${tableName} WHERE "mcpServerId" = $1 ORDER BY "${field}" ${direction} LIMIT $2 OFFSET $3`,
6460
+ [mcpServerId, limitValue, offset]
6461
+ );
6462
+ const versions = (dataResult || []).map((row) => this.parseVersionRow(row));
6463
+ return {
6464
+ versions,
6465
+ total,
6466
+ page,
6467
+ perPage: perPageForResponse,
6468
+ hasMore: perPageInput === false ? false : offset + perPage < total
6469
+ };
6470
+ } catch (error) {
6471
+ if (error instanceof MastraError) throw error;
6472
+ throw new MastraError(
6473
+ {
6474
+ id: createStorageErrorId("PG", "LIST_MCP_SERVER_VERSIONS", "FAILED"),
6475
+ domain: ErrorDomain.STORAGE,
6476
+ category: ErrorCategory.THIRD_PARTY,
6477
+ details: { mcpServerId }
6478
+ },
6479
+ error
6480
+ );
6481
+ }
6482
+ }
6483
+ async deleteVersion(id) {
6484
+ try {
6485
+ const tableName = getTableName2({
6486
+ indexName: TABLE_MCP_SERVER_VERSIONS,
6487
+ schemaName: getSchemaName2(this.#schema)
6488
+ });
6489
+ await this.#db.client.none(`DELETE FROM ${tableName} WHERE id = $1`, [id]);
6490
+ } catch (error) {
6491
+ if (error instanceof MastraError) throw error;
6492
+ throw new MastraError(
6493
+ {
6494
+ id: createStorageErrorId("PG", "DELETE_MCP_SERVER_VERSION", "FAILED"),
6495
+ domain: ErrorDomain.STORAGE,
6496
+ category: ErrorCategory.THIRD_PARTY,
6497
+ details: { versionId: id }
6498
+ },
6499
+ error
6500
+ );
6501
+ }
6502
+ }
6503
+ async deleteVersionsByParentId(entityId) {
6504
+ try {
6505
+ const tableName = getTableName2({
6506
+ indexName: TABLE_MCP_SERVER_VERSIONS,
6507
+ schemaName: getSchemaName2(this.#schema)
6508
+ });
6509
+ await this.#db.client.none(`DELETE FROM ${tableName} WHERE "mcpServerId" = $1`, [entityId]);
6510
+ } catch (error) {
6511
+ if (error instanceof MastraError) throw error;
6512
+ throw new MastraError(
6513
+ {
6514
+ id: createStorageErrorId("PG", "DELETE_MCP_SERVER_VERSIONS_BY_MCP_SERVER_ID", "FAILED"),
6515
+ domain: ErrorDomain.STORAGE,
6516
+ category: ErrorCategory.THIRD_PARTY,
6517
+ details: { mcpServerId: entityId }
6518
+ },
6519
+ error
6520
+ );
6521
+ }
6522
+ }
6523
+ async countVersions(mcpServerId) {
6524
+ try {
6525
+ const tableName = getTableName2({
6526
+ indexName: TABLE_MCP_SERVER_VERSIONS,
6527
+ schemaName: getSchemaName2(this.#schema)
6528
+ });
6529
+ const result = await this.#db.client.one(`SELECT COUNT(*) as count FROM ${tableName} WHERE "mcpServerId" = $1`, [
6530
+ mcpServerId
6531
+ ]);
6532
+ return parseInt(result.count, 10);
6533
+ } catch (error) {
6534
+ if (error instanceof MastraError) throw error;
6535
+ throw new MastraError(
6536
+ {
6537
+ id: createStorageErrorId("PG", "COUNT_MCP_SERVER_VERSIONS", "FAILED"),
6538
+ domain: ErrorDomain.STORAGE,
6539
+ category: ErrorCategory.THIRD_PARTY,
6540
+ details: { mcpServerId }
6541
+ },
6542
+ error
6543
+ );
6544
+ }
6545
+ }
6546
+ // ==========================================================================
6547
+ // Private Helper Methods
6548
+ // ==========================================================================
6549
+ parseJson(value, fieldName) {
6550
+ if (!value) return void 0;
6551
+ if (typeof value !== "string") return value;
6552
+ try {
6553
+ return JSON.parse(value);
6554
+ } catch (error) {
6555
+ if (error instanceof MastraError) throw error;
6556
+ const details = {
6557
+ valueLength: String(value.length)
6558
+ };
6559
+ if (fieldName) {
6560
+ details.field = fieldName;
6561
+ }
6562
+ throw new MastraError(
6563
+ {
6564
+ id: createStorageErrorId("PG", "PARSE_JSON", "INVALID_JSON"),
6565
+ domain: ErrorDomain.STORAGE,
6566
+ category: ErrorCategory.SYSTEM,
6567
+ text: `Failed to parse JSON${fieldName ? ` for field "${fieldName}"` : ""}: ${error instanceof Error ? error.message : "Unknown error"}`,
6568
+ details
6569
+ },
6570
+ error
6571
+ );
6572
+ }
6573
+ }
6574
+ parseMCPServerRow(row) {
6575
+ return {
6576
+ id: row.id,
6577
+ status: row.status,
6578
+ activeVersionId: row.activeVersionId,
6579
+ authorId: row.authorId,
6580
+ metadata: this.parseJson(row.metadata, "metadata"),
6581
+ createdAt: new Date(row.createdAtZ || row.createdAt),
6582
+ updatedAt: new Date(row.updatedAtZ || row.updatedAt)
6583
+ };
6584
+ }
6585
+ parseVersionRow(row) {
6586
+ return {
6587
+ id: row.id,
6588
+ mcpServerId: row.mcpServerId,
6589
+ versionNumber: row.versionNumber,
6590
+ name: row.name,
6591
+ version: row.version,
6592
+ description: row.description,
6593
+ instructions: row.instructions,
6594
+ repository: this.parseJson(row.repository, "repository"),
6595
+ releaseDate: row.releaseDate,
6596
+ isLatest: row.isLatest,
6597
+ packageCanonical: row.packageCanonical,
6598
+ tools: this.parseJson(row.tools, "tools"),
6599
+ agents: this.parseJson(row.agents, "agents"),
6600
+ workflows: this.parseJson(row.workflows, "workflows"),
6601
+ changedFields: this.parseJson(row.changedFields, "changedFields"),
6602
+ changeMessage: row.changeMessage,
6603
+ createdAt: new Date(row.createdAtZ || row.createdAt)
6604
+ };
6605
+ }
6606
+ };
5965
6607
  var OM_TABLE = "mastra_observational_memory";
5966
6608
  var _omTableSchema;
5967
6609
  try {
@@ -7906,32 +8548,39 @@ var MemoryPG = class _MemoryPG extends MemoryStorage {
7906
8548
  const targetMessageTokens = Math.max(0, input.currentPendingTokens - retentionFloor);
7907
8549
  let cumulativeMessageTokens = 0;
7908
8550
  let chunksToActivate = 0;
7909
- let bestBoundary = 0;
7910
- let bestBoundaryMessageTokens = 0;
8551
+ let bestOverBoundary = 0;
8552
+ let bestOverTokens = 0;
8553
+ let bestUnderBoundary = 0;
8554
+ let bestUnderTokens = 0;
7911
8555
  for (let i = 0; i < chunks.length; i++) {
7912
8556
  cumulativeMessageTokens += chunks[i].messageTokens ?? 0;
7913
8557
  const boundary = i + 1;
7914
- const isUnder = cumulativeMessageTokens <= targetMessageTokens;
7915
- const bestIsUnder = bestBoundaryMessageTokens <= targetMessageTokens;
7916
- if (bestBoundary === 0) {
7917
- bestBoundary = boundary;
7918
- bestBoundaryMessageTokens = cumulativeMessageTokens;
7919
- } else if (isUnder && !bestIsUnder) {
7920
- bestBoundary = boundary;
7921
- bestBoundaryMessageTokens = cumulativeMessageTokens;
7922
- } else if (isUnder && bestIsUnder) {
7923
- if (cumulativeMessageTokens > bestBoundaryMessageTokens) {
7924
- bestBoundary = boundary;
7925
- bestBoundaryMessageTokens = cumulativeMessageTokens;
8558
+ if (cumulativeMessageTokens >= targetMessageTokens) {
8559
+ if (bestOverBoundary === 0 || cumulativeMessageTokens < bestOverTokens) {
8560
+ bestOverBoundary = boundary;
8561
+ bestOverTokens = cumulativeMessageTokens;
7926
8562
  }
7927
- } else if (!isUnder && !bestIsUnder) {
7928
- if (cumulativeMessageTokens < bestBoundaryMessageTokens) {
7929
- bestBoundary = boundary;
7930
- bestBoundaryMessageTokens = cumulativeMessageTokens;
8563
+ } else {
8564
+ if (cumulativeMessageTokens > bestUnderTokens) {
8565
+ bestUnderBoundary = boundary;
8566
+ bestUnderTokens = cumulativeMessageTokens;
7931
8567
  }
7932
8568
  }
7933
8569
  }
7934
- chunksToActivate = bestBoundary === 0 ? 1 : bestBoundary;
8570
+ const maxOvershoot = retentionFloor * 0.95;
8571
+ const overshoot = bestOverTokens - targetMessageTokens;
8572
+ const remainingAfterOver = input.currentPendingTokens - bestOverTokens;
8573
+ if (input.forceMaxActivation && bestOverBoundary > 0) {
8574
+ chunksToActivate = bestOverBoundary;
8575
+ } else if (bestOverBoundary > 0 && overshoot <= maxOvershoot && (remainingAfterOver >= 1e3 || retentionFloor === 0)) {
8576
+ chunksToActivate = bestOverBoundary;
8577
+ } else if (bestUnderBoundary > 0) {
8578
+ chunksToActivate = bestUnderBoundary;
8579
+ } else if (bestOverBoundary > 0) {
8580
+ chunksToActivate = bestOverBoundary;
8581
+ } else {
8582
+ chunksToActivate = 1;
8583
+ }
7935
8584
  const activatedChunks = chunks.slice(0, chunksToActivate);
7936
8585
  const remainingChunks = chunks.slice(chunksToActivate);
7937
8586
  const activatedContent = activatedChunks.map((c) => c.observations).join("\n\n");
@@ -7970,6 +8619,7 @@ var MemoryPG = class _MemoryPG extends MemoryStorage {
7970
8619
  input.id
7971
8620
  ]
7972
8621
  );
8622
+ const latestChunkHints = activatedChunks[activatedChunks.length - 1];
7973
8623
  return {
7974
8624
  chunksActivated: activatedChunks.length,
7975
8625
  messageTokensActivated: activatedMessageTokens,
@@ -7984,7 +8634,9 @@ var MemoryPG = class _MemoryPG extends MemoryStorage {
7984
8634
  observationTokens: c.tokenCount,
7985
8635
  messageCount: c.messageIds.length,
7986
8636
  observations: c.observations
7987
- }))
8637
+ })),
8638
+ suggestedContinuation: latestChunkHints?.suggestedContinuation ?? void 0,
8639
+ currentTask: latestChunkHints?.currentTask ?? void 0
7988
8640
  };
7989
8641
  } catch (error) {
7990
8642
  if (error instanceof MastraError) {
@@ -8768,7 +9420,7 @@ var ObservabilityPG = class _ObservabilityPG extends ObservabilityStorage {
8768
9420
  }
8769
9421
  }
8770
9422
  };
8771
- var SNAPSHOT_FIELDS2 = ["name", "description", "content", "rules"];
9423
+ var SNAPSHOT_FIELDS3 = ["name", "description", "content", "rules"];
8772
9424
  var PromptBlocksPG = class _PromptBlocksPG extends PromptBlocksStorage {
8773
9425
  #db;
8774
9426
  #schema;
@@ -8914,7 +9566,7 @@ var PromptBlocksPG = class _PromptBlocksPG extends PromptBlocksStorage {
8914
9566
  blockId: promptBlock.id,
8915
9567
  versionNumber: 1,
8916
9568
  ...snapshotConfig,
8917
- changedFields: [...SNAPSHOT_FIELDS2],
9569
+ changedFields: [...SNAPSHOT_FIELDS3],
8918
9570
  changeMessage: "Initial version"
8919
9571
  });
8920
9572
  return {
@@ -9405,7 +10057,7 @@ var PromptBlocksPG = class _PromptBlocksPG extends PromptBlocksStorage {
9405
10057
  };
9406
10058
  }
9407
10059
  };
9408
- var SNAPSHOT_FIELDS3 = [
10060
+ var SNAPSHOT_FIELDS4 = [
9409
10061
  "name",
9410
10062
  "description",
9411
10063
  "type",
@@ -9565,7 +10217,7 @@ var ScorerDefinitionsPG = class _ScorerDefinitionsPG extends ScorerDefinitionsSt
9565
10217
  scorerDefinitionId: scorerDefinition.id,
9566
10218
  versionNumber: 1,
9567
10219
  ...snapshotConfig,
9568
- changedFields: [...SNAPSHOT_FIELDS3],
10220
+ changedFields: [...SNAPSHOT_FIELDS4],
9569
10221
  changeMessage: "Initial version"
9570
10222
  });
9571
10223
  return {
@@ -10481,7 +11133,7 @@ var ScoresPG = class _ScoresPG extends ScoresStorage {
10481
11133
  }
10482
11134
  }
10483
11135
  };
10484
- var SNAPSHOT_FIELDS4 = [
11136
+ var SNAPSHOT_FIELDS5 = [
10485
11137
  "name",
10486
11138
  "description",
10487
11139
  "instructions",
@@ -10601,7 +11253,7 @@ var SkillsPG = class _SkillsPG extends SkillsStorage {
10601
11253
  skillId: skill.id,
10602
11254
  versionNumber: 1,
10603
11255
  ...snapshotConfig,
10604
- changedFields: [...SNAPSHOT_FIELDS4],
11256
+ changedFields: [...SNAPSHOT_FIELDS5],
10605
11257
  changeMessage: "Initial version"
10606
11258
  });
10607
11259
  return {
@@ -10652,7 +11304,7 @@ var SkillsPG = class _SkillsPG extends SkillsStorage {
10652
11304
  }
10653
11305
  const { authorId, activeVersionId, status, ...configFields } = updates;
10654
11306
  let versionCreated = false;
10655
- const hasConfigUpdate = SNAPSHOT_FIELDS4.some((field) => field in configFields);
11307
+ const hasConfigUpdate = SNAPSHOT_FIELDS5.some((field) => field in configFields);
10656
11308
  if (hasConfigUpdate) {
10657
11309
  const latestVersion = await this.getLatestVersion(id);
10658
11310
  if (!latestVersion) {
@@ -10674,7 +11326,7 @@ var SkillsPG = class _SkillsPG extends SkillsStorage {
10674
11326
  ...latestConfig
10675
11327
  } = latestVersion;
10676
11328
  const newConfig = { ...latestConfig, ...configFields };
10677
- const changedFields = SNAPSHOT_FIELDS4.filter(
11329
+ const changedFields = SNAPSHOT_FIELDS5.filter(
10678
11330
  (field) => field in configFields && JSON.stringify(configFields[field]) !== JSON.stringify(latestConfig[field])
10679
11331
  );
10680
11332
  if (changedFields.length > 0) {
@@ -11467,7 +12119,7 @@ var WorkflowsPG = class _WorkflowsPG extends WorkflowsStorage {
11467
12119
  }
11468
12120
  }
11469
12121
  };
11470
- var SNAPSHOT_FIELDS5 = [
12122
+ var SNAPSHOT_FIELDS6 = [
11471
12123
  "name",
11472
12124
  "description",
11473
12125
  "filesystem",
@@ -11596,7 +12248,7 @@ var WorkspacesPG = class _WorkspacesPG extends WorkspacesStorage {
11596
12248
  workspaceId: workspace.id,
11597
12249
  versionNumber: 1,
11598
12250
  ...snapshotConfig,
11599
- changedFields: [...SNAPSHOT_FIELDS5],
12251
+ changedFields: [...SNAPSHOT_FIELDS6],
11600
12252
  changeMessage: "Initial version"
11601
12253
  });
11602
12254
  return {
@@ -11648,7 +12300,7 @@ var WorkspacesPG = class _WorkspacesPG extends WorkspacesStorage {
11648
12300
  }
11649
12301
  const { authorId, activeVersionId, metadata, status, ...configFields } = updates;
11650
12302
  let versionCreated = false;
11651
- const hasConfigUpdate = SNAPSHOT_FIELDS5.some((field) => field in configFields);
12303
+ const hasConfigUpdate = SNAPSHOT_FIELDS6.some((field) => field in configFields);
11652
12304
  if (hasConfigUpdate) {
11653
12305
  const latestVersion = await this.getLatestVersion(id);
11654
12306
  if (!latestVersion) {
@@ -11670,7 +12322,7 @@ var WorkspacesPG = class _WorkspacesPG extends WorkspacesStorage {
11670
12322
  ...latestConfig
11671
12323
  } = latestVersion;
11672
12324
  const newConfig = { ...latestConfig, ...configFields };
11673
- const changedFields = SNAPSHOT_FIELDS5.filter(
12325
+ const changedFields = SNAPSHOT_FIELDS6.filter(
11674
12326
  (field) => field in configFields && JSON.stringify(configFields[field]) !== JSON.stringify(latestConfig[field])
11675
12327
  );
11676
12328
  if (changedFields.length > 0) {
@@ -12213,6 +12865,7 @@ var PostgresStore = class extends MastraCompositeStore {
12213
12865
  promptBlocks: new PromptBlocksPG(domainConfig),
12214
12866
  scorerDefinitions: new ScorerDefinitionsPG(domainConfig),
12215
12867
  mcpClients: new MCPClientsPG(domainConfig),
12868
+ mcpServers: new MCPServersPG(domainConfig),
12216
12869
  workspaces: new WorkspacesPG(domainConfig),
12217
12870
  skills: new SkillsPG(domainConfig),
12218
12871
  blobs: new BlobsPG(domainConfig),
@@ -12406,6 +13059,6 @@ Example Complex Query:
12406
13059
  ]
12407
13060
  }`;
12408
13061
 
12409
- export { AgentsPG, BlobsPG, DatasetsPG, ExperimentsPG, MCPClientsPG, MemoryPG, ObservabilityPG, PGVECTOR_PROMPT, PgVector, PoolAdapter, PostgresStore, PromptBlocksPG, ScorerDefinitionsPG, ScoresPG, SkillsPG, WorkflowsPG, WorkspacesPG, exportSchemas };
13062
+ export { AgentsPG, BlobsPG, DatasetsPG, ExperimentsPG, MCPClientsPG, MCPServersPG, MemoryPG, ObservabilityPG, PGVECTOR_PROMPT, PgVector, PoolAdapter, PostgresStore, PromptBlocksPG, ScorerDefinitionsPG, ScoresPG, SkillsPG, WorkflowsPG, WorkspacesPG, exportSchemas };
12410
13063
  //# sourceMappingURL=index.js.map
12411
13064
  //# sourceMappingURL=index.js.map