@mastra/libsql 1.5.0-alpha.0 → 1.6.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,6 +1,6 @@
1
1
  import { createClient } from '@libsql/client';
2
2
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
3
- import { createVectorErrorId, AgentsStorage, AGENTS_SCHEMA, TABLE_AGENTS, AGENT_VERSIONS_SCHEMA, TABLE_AGENT_VERSIONS, createStorageErrorId, normalizePerPage, calculatePagination, BlobStore, TABLE_SKILL_BLOBS, SKILL_BLOBS_SCHEMA, DatasetsStorage, DATASETS_SCHEMA, TABLE_DATASETS, DATASET_ITEMS_SCHEMA, TABLE_DATASET_ITEMS, DATASET_VERSIONS_SCHEMA, TABLE_DATASET_VERSIONS, ensureDate, safelyParseJSON, TABLE_EXPERIMENT_RESULTS, TABLE_EXPERIMENTS, ExperimentsStorage, EXPERIMENTS_SCHEMA, EXPERIMENT_RESULTS_SCHEMA, MCPClientsStorage, MCP_CLIENTS_SCHEMA, TABLE_MCP_CLIENTS, MCP_CLIENT_VERSIONS_SCHEMA, TABLE_MCP_CLIENT_VERSIONS, MemoryStorage, TABLE_SCHEMAS, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, ObservabilityStorage, SPAN_SCHEMA, TABLE_SPANS, listTracesArgsSchema, toTraceSpans, PromptBlocksStorage, PROMPT_BLOCKS_SCHEMA, TABLE_PROMPT_BLOCKS, PROMPT_BLOCK_VERSIONS_SCHEMA, TABLE_PROMPT_BLOCK_VERSIONS, ScorerDefinitionsStorage, SCORER_DEFINITIONS_SCHEMA, TABLE_SCORER_DEFINITIONS, SCORER_DEFINITION_VERSIONS_SCHEMA, TABLE_SCORER_DEFINITION_VERSIONS, ScoresStorage, SCORERS_SCHEMA, TABLE_SCORERS, transformScoreRow, SkillsStorage, SKILLS_SCHEMA, TABLE_SKILLS, SKILL_VERSIONS_SCHEMA, TABLE_SKILL_VERSIONS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, WorkspacesStorage, WORKSPACES_SCHEMA, TABLE_WORKSPACES, WORKSPACE_VERSIONS_SCHEMA, TABLE_WORKSPACE_VERSIONS, MastraCompositeStore, TraceStatus, getSqlType } from '@mastra/core/storage';
3
+ import { createVectorErrorId, AgentsStorage, AGENTS_SCHEMA, TABLE_AGENTS, AGENT_VERSIONS_SCHEMA, TABLE_AGENT_VERSIONS, createStorageErrorId, normalizePerPage, calculatePagination, BlobStore, TABLE_SKILL_BLOBS, SKILL_BLOBS_SCHEMA, DatasetsStorage, DATASETS_SCHEMA, TABLE_DATASETS, DATASET_ITEMS_SCHEMA, TABLE_DATASET_ITEMS, DATASET_VERSIONS_SCHEMA, TABLE_DATASET_VERSIONS, ensureDate, safelyParseJSON, TABLE_EXPERIMENT_RESULTS, TABLE_EXPERIMENTS, ExperimentsStorage, EXPERIMENTS_SCHEMA, EXPERIMENT_RESULTS_SCHEMA, MCPClientsStorage, MCP_CLIENTS_SCHEMA, TABLE_MCP_CLIENTS, MCP_CLIENT_VERSIONS_SCHEMA, TABLE_MCP_CLIENT_VERSIONS, MCPServersStorage, MCP_SERVERS_SCHEMA, TABLE_MCP_SERVERS, MCP_SERVER_VERSIONS_SCHEMA, TABLE_MCP_SERVER_VERSIONS, MemoryStorage, TABLE_SCHEMAS, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, ObservabilityStorage, SPAN_SCHEMA, TABLE_SPANS, listTracesArgsSchema, toTraceSpans, PromptBlocksStorage, PROMPT_BLOCKS_SCHEMA, TABLE_PROMPT_BLOCKS, PROMPT_BLOCK_VERSIONS_SCHEMA, TABLE_PROMPT_BLOCK_VERSIONS, ScorerDefinitionsStorage, SCORER_DEFINITIONS_SCHEMA, TABLE_SCORER_DEFINITIONS, SCORER_DEFINITION_VERSIONS_SCHEMA, TABLE_SCORER_DEFINITION_VERSIONS, ScoresStorage, SCORERS_SCHEMA, TABLE_SCORERS, transformScoreRow, SkillsStorage, SKILLS_SCHEMA, TABLE_SKILLS, SKILL_VERSIONS_SCHEMA, TABLE_SKILL_VERSIONS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, WorkspacesStorage, WORKSPACES_SCHEMA, TABLE_WORKSPACES, WORKSPACE_VERSIONS_SCHEMA, TABLE_WORKSPACE_VERSIONS, MastraCompositeStore, TraceStatus, getSqlType } from '@mastra/core/storage';
4
4
  import { parseSqlIdentifier, parseFieldKey } from '@mastra/core/utils';
5
5
  import { MastraVector, validateTopK, validateUpsertInput } from '@mastra/core/vector';
6
6
  import { BaseFilterTranslator } from '@mastra/core/vector/filter';
@@ -4630,6 +4630,490 @@ var MCPClientsLibSQL = class extends MCPClientsStorage {
4630
4630
  };
4631
4631
  }
4632
4632
  };
4633
+ var MCPServersLibSQL = class extends MCPServersStorage {
4634
+ #db;
4635
+ #client;
4636
+ constructor(config) {
4637
+ super();
4638
+ const client = resolveClient(config);
4639
+ this.#client = client;
4640
+ this.#db = new LibSQLDB({ client, maxRetries: config.maxRetries, initialBackoffMs: config.initialBackoffMs });
4641
+ }
4642
+ async init() {
4643
+ await this.#db.createTable({ tableName: TABLE_MCP_SERVERS, schema: MCP_SERVERS_SCHEMA });
4644
+ await this.#db.createTable({
4645
+ tableName: TABLE_MCP_SERVER_VERSIONS,
4646
+ schema: MCP_SERVER_VERSIONS_SCHEMA
4647
+ });
4648
+ await this.#client.execute(
4649
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_mcp_server_versions_server_version ON "${TABLE_MCP_SERVER_VERSIONS}" ("mcpServerId", "versionNumber")`
4650
+ );
4651
+ }
4652
+ async dangerouslyClearAll() {
4653
+ await this.#db.deleteData({ tableName: TABLE_MCP_SERVERS });
4654
+ await this.#db.deleteData({ tableName: TABLE_MCP_SERVER_VERSIONS });
4655
+ }
4656
+ // ==========================================================================
4657
+ // MCP Server CRUD
4658
+ // ==========================================================================
4659
+ async getById(id) {
4660
+ try {
4661
+ const result = await this.#client.execute({
4662
+ sql: `SELECT ${buildSelectColumns(TABLE_MCP_SERVERS)} FROM "${TABLE_MCP_SERVERS}" WHERE id = ?`,
4663
+ args: [id]
4664
+ });
4665
+ const row = result.rows?.[0];
4666
+ return row ? this.#parseMCPServerRow(row) : null;
4667
+ } catch (error) {
4668
+ if (error instanceof MastraError) throw error;
4669
+ throw new MastraError(
4670
+ {
4671
+ id: createStorageErrorId("LIBSQL", "GET_MCP_SERVER", "FAILED"),
4672
+ domain: ErrorDomain.STORAGE,
4673
+ category: ErrorCategory.THIRD_PARTY
4674
+ },
4675
+ error
4676
+ );
4677
+ }
4678
+ }
4679
+ async create(input) {
4680
+ const { mcpServer } = input;
4681
+ try {
4682
+ const now = /* @__PURE__ */ new Date();
4683
+ await this.#db.insert({
4684
+ tableName: TABLE_MCP_SERVERS,
4685
+ record: {
4686
+ id: mcpServer.id,
4687
+ status: "draft",
4688
+ activeVersionId: null,
4689
+ authorId: mcpServer.authorId ?? null,
4690
+ metadata: mcpServer.metadata ?? null,
4691
+ createdAt: now.toISOString(),
4692
+ updatedAt: now.toISOString()
4693
+ }
4694
+ });
4695
+ const { id: _id, authorId: _authorId, metadata: _metadata, ...snapshotConfig } = mcpServer;
4696
+ const versionId = crypto.randomUUID();
4697
+ try {
4698
+ await this.createVersion({
4699
+ id: versionId,
4700
+ mcpServerId: mcpServer.id,
4701
+ versionNumber: 1,
4702
+ ...snapshotConfig,
4703
+ changedFields: Object.keys(snapshotConfig),
4704
+ changeMessage: "Initial version"
4705
+ });
4706
+ } catch (versionError) {
4707
+ await this.#db.delete({ tableName: TABLE_MCP_SERVERS, keys: { id: mcpServer.id } });
4708
+ throw versionError;
4709
+ }
4710
+ return {
4711
+ id: mcpServer.id,
4712
+ status: "draft",
4713
+ activeVersionId: void 0,
4714
+ authorId: mcpServer.authorId,
4715
+ metadata: mcpServer.metadata,
4716
+ createdAt: now,
4717
+ updatedAt: now
4718
+ };
4719
+ } catch (error) {
4720
+ if (error instanceof MastraError) throw error;
4721
+ throw new MastraError(
4722
+ {
4723
+ id: createStorageErrorId("LIBSQL", "CREATE_MCP_SERVER", "FAILED"),
4724
+ domain: ErrorDomain.STORAGE,
4725
+ category: ErrorCategory.THIRD_PARTY
4726
+ },
4727
+ error
4728
+ );
4729
+ }
4730
+ }
4731
+ async update(input) {
4732
+ const { id, ...updates } = input;
4733
+ try {
4734
+ const existing = await this.getById(id);
4735
+ if (!existing) {
4736
+ throw new Error(`MCP server with id ${id} not found`);
4737
+ }
4738
+ const { authorId, activeVersionId, metadata, status } = updates;
4739
+ const updateData = {
4740
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
4741
+ };
4742
+ if (authorId !== void 0) updateData.authorId = authorId;
4743
+ if (activeVersionId !== void 0) updateData.activeVersionId = activeVersionId;
4744
+ if (status !== void 0) updateData.status = status;
4745
+ if (metadata !== void 0) {
4746
+ updateData.metadata = { ...existing.metadata, ...metadata };
4747
+ }
4748
+ await this.#db.update({
4749
+ tableName: TABLE_MCP_SERVERS,
4750
+ keys: { id },
4751
+ data: updateData
4752
+ });
4753
+ const updated = await this.getById(id);
4754
+ if (!updated) {
4755
+ throw new MastraError({
4756
+ id: createStorageErrorId("LIBSQL", "UPDATE_MCP_SERVER", "NOT_FOUND_AFTER_UPDATE"),
4757
+ domain: ErrorDomain.STORAGE,
4758
+ category: ErrorCategory.SYSTEM,
4759
+ text: `MCP server ${id} not found after update`,
4760
+ details: { id }
4761
+ });
4762
+ }
4763
+ return updated;
4764
+ } catch (error) {
4765
+ if (error instanceof MastraError) throw error;
4766
+ throw new MastraError(
4767
+ {
4768
+ id: createStorageErrorId("LIBSQL", "UPDATE_MCP_SERVER", "FAILED"),
4769
+ domain: ErrorDomain.STORAGE,
4770
+ category: ErrorCategory.THIRD_PARTY
4771
+ },
4772
+ error
4773
+ );
4774
+ }
4775
+ }
4776
+ async delete(id) {
4777
+ try {
4778
+ await this.deleteVersionsByParentId(id);
4779
+ await this.#client.execute({
4780
+ sql: `DELETE FROM "${TABLE_MCP_SERVERS}" WHERE "id" = ?`,
4781
+ args: [id]
4782
+ });
4783
+ } catch (error) {
4784
+ if (error instanceof MastraError) throw error;
4785
+ throw new MastraError(
4786
+ {
4787
+ id: createStorageErrorId("LIBSQL", "DELETE_MCP_SERVER", "FAILED"),
4788
+ domain: ErrorDomain.STORAGE,
4789
+ category: ErrorCategory.THIRD_PARTY
4790
+ },
4791
+ error
4792
+ );
4793
+ }
4794
+ }
4795
+ async list(args) {
4796
+ try {
4797
+ const { page = 0, perPage: perPageInput, orderBy, authorId, metadata, status = "published" } = args || {};
4798
+ const { field, direction } = this.parseOrderBy(orderBy);
4799
+ const conditions = [];
4800
+ const queryParams = [];
4801
+ conditions.push("status = ?");
4802
+ queryParams.push(status);
4803
+ if (authorId !== void 0) {
4804
+ conditions.push("authorId = ?");
4805
+ queryParams.push(authorId);
4806
+ }
4807
+ if (metadata && Object.keys(metadata).length > 0) {
4808
+ for (const [key, value] of Object.entries(metadata)) {
4809
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
4810
+ throw new MastraError({
4811
+ id: createStorageErrorId("LIBSQL", "LIST_MCP_SERVERS", "INVALID_METADATA_KEY"),
4812
+ domain: ErrorDomain.STORAGE,
4813
+ category: ErrorCategory.USER,
4814
+ text: `Invalid metadata key: ${key}. Keys must be alphanumeric with underscores.`,
4815
+ details: { key }
4816
+ });
4817
+ }
4818
+ conditions.push(`json_extract(metadata, '$.${key}') = ?`);
4819
+ queryParams.push(typeof value === "string" ? value : JSON.stringify(value));
4820
+ }
4821
+ }
4822
+ const whereClause = `WHERE ${conditions.join(" AND ")}`;
4823
+ const countResult = await this.#client.execute({
4824
+ sql: `SELECT COUNT(*) as count FROM "${TABLE_MCP_SERVERS}" ${whereClause}`,
4825
+ args: queryParams
4826
+ });
4827
+ const total = Number(countResult.rows?.[0]?.count ?? 0);
4828
+ if (total === 0) {
4829
+ return {
4830
+ mcpServers: [],
4831
+ total: 0,
4832
+ page,
4833
+ perPage: perPageInput ?? 100,
4834
+ hasMore: false
4835
+ };
4836
+ }
4837
+ const perPage = normalizePerPage(perPageInput, 100);
4838
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
4839
+ const limitValue = perPageInput === false ? total : perPage;
4840
+ const end = perPageInput === false ? total : start + perPage;
4841
+ const result = await this.#client.execute({
4842
+ sql: `SELECT ${buildSelectColumns(TABLE_MCP_SERVERS)} FROM "${TABLE_MCP_SERVERS}" ${whereClause} ORDER BY ${field} ${direction} LIMIT ? OFFSET ?`,
4843
+ args: [...queryParams, limitValue, start]
4844
+ });
4845
+ const mcpServers = result.rows?.map((row) => this.#parseMCPServerRow(row)) ?? [];
4846
+ return {
4847
+ mcpServers,
4848
+ total,
4849
+ page,
4850
+ perPage: perPageForResponse,
4851
+ hasMore: end < total
4852
+ };
4853
+ } catch (error) {
4854
+ if (error instanceof MastraError) throw error;
4855
+ throw new MastraError(
4856
+ {
4857
+ id: createStorageErrorId("LIBSQL", "LIST_MCP_SERVERS", "FAILED"),
4858
+ domain: ErrorDomain.STORAGE,
4859
+ category: ErrorCategory.THIRD_PARTY
4860
+ },
4861
+ error
4862
+ );
4863
+ }
4864
+ }
4865
+ // ==========================================================================
4866
+ // MCP Server Version Methods
4867
+ // ==========================================================================
4868
+ async createVersion(input) {
4869
+ try {
4870
+ const now = /* @__PURE__ */ new Date();
4871
+ await this.#db.insert({
4872
+ tableName: TABLE_MCP_SERVER_VERSIONS,
4873
+ record: {
4874
+ id: input.id,
4875
+ mcpServerId: input.mcpServerId,
4876
+ versionNumber: input.versionNumber,
4877
+ name: input.name,
4878
+ version: input.version,
4879
+ description: input.description ?? null,
4880
+ instructions: input.instructions ?? null,
4881
+ repository: input.repository ?? null,
4882
+ releaseDate: input.releaseDate ?? null,
4883
+ isLatest: input.isLatest ?? null,
4884
+ packageCanonical: input.packageCanonical ?? null,
4885
+ tools: input.tools ?? null,
4886
+ agents: input.agents ?? null,
4887
+ workflows: input.workflows ?? null,
4888
+ changedFields: input.changedFields ?? null,
4889
+ changeMessage: input.changeMessage ?? null,
4890
+ createdAt: now.toISOString()
4891
+ }
4892
+ });
4893
+ return {
4894
+ ...input,
4895
+ createdAt: now
4896
+ };
4897
+ } catch (error) {
4898
+ if (error instanceof MastraError) throw error;
4899
+ throw new MastraError(
4900
+ {
4901
+ id: createStorageErrorId("LIBSQL", "CREATE_MCP_SERVER_VERSION", "FAILED"),
4902
+ domain: ErrorDomain.STORAGE,
4903
+ category: ErrorCategory.THIRD_PARTY
4904
+ },
4905
+ error
4906
+ );
4907
+ }
4908
+ }
4909
+ async getVersion(id) {
4910
+ try {
4911
+ const result = await this.#client.execute({
4912
+ sql: `SELECT ${buildSelectColumns(TABLE_MCP_SERVER_VERSIONS)} FROM "${TABLE_MCP_SERVER_VERSIONS}" WHERE id = ?`,
4913
+ args: [id]
4914
+ });
4915
+ const row = result.rows?.[0];
4916
+ return row ? this.#parseVersionRow(row) : null;
4917
+ } catch (error) {
4918
+ if (error instanceof MastraError) throw error;
4919
+ throw new MastraError(
4920
+ {
4921
+ id: createStorageErrorId("LIBSQL", "GET_MCP_SERVER_VERSION", "FAILED"),
4922
+ domain: ErrorDomain.STORAGE,
4923
+ category: ErrorCategory.THIRD_PARTY
4924
+ },
4925
+ error
4926
+ );
4927
+ }
4928
+ }
4929
+ async getVersionByNumber(mcpServerId, versionNumber) {
4930
+ try {
4931
+ const result = await this.#client.execute({
4932
+ sql: `SELECT ${buildSelectColumns(TABLE_MCP_SERVER_VERSIONS)} FROM "${TABLE_MCP_SERVER_VERSIONS}" WHERE mcpServerId = ? AND versionNumber = ?`,
4933
+ args: [mcpServerId, versionNumber]
4934
+ });
4935
+ const row = result.rows?.[0];
4936
+ return row ? this.#parseVersionRow(row) : null;
4937
+ } catch (error) {
4938
+ if (error instanceof MastraError) throw error;
4939
+ throw new MastraError(
4940
+ {
4941
+ id: createStorageErrorId("LIBSQL", "GET_MCP_SERVER_VERSION_BY_NUMBER", "FAILED"),
4942
+ domain: ErrorDomain.STORAGE,
4943
+ category: ErrorCategory.THIRD_PARTY
4944
+ },
4945
+ error
4946
+ );
4947
+ }
4948
+ }
4949
+ async getLatestVersion(mcpServerId) {
4950
+ try {
4951
+ const result = await this.#client.execute({
4952
+ sql: `SELECT ${buildSelectColumns(TABLE_MCP_SERVER_VERSIONS)} FROM "${TABLE_MCP_SERVER_VERSIONS}" WHERE mcpServerId = ? ORDER BY versionNumber DESC LIMIT 1`,
4953
+ args: [mcpServerId]
4954
+ });
4955
+ const row = result.rows?.[0];
4956
+ return row ? this.#parseVersionRow(row) : null;
4957
+ } catch (error) {
4958
+ if (error instanceof MastraError) throw error;
4959
+ throw new MastraError(
4960
+ {
4961
+ id: createStorageErrorId("LIBSQL", "GET_LATEST_MCP_SERVER_VERSION", "FAILED"),
4962
+ domain: ErrorDomain.STORAGE,
4963
+ category: ErrorCategory.THIRD_PARTY
4964
+ },
4965
+ error
4966
+ );
4967
+ }
4968
+ }
4969
+ async listVersions(input) {
4970
+ try {
4971
+ const { mcpServerId, page = 0, perPage: perPageInput, orderBy } = input;
4972
+ const { field, direction } = this.parseVersionOrderBy(orderBy);
4973
+ const countResult = await this.#client.execute({
4974
+ sql: `SELECT COUNT(*) as count FROM "${TABLE_MCP_SERVER_VERSIONS}" WHERE mcpServerId = ?`,
4975
+ args: [mcpServerId]
4976
+ });
4977
+ const total = Number(countResult.rows?.[0]?.count ?? 0);
4978
+ if (total === 0) {
4979
+ return {
4980
+ versions: [],
4981
+ total: 0,
4982
+ page,
4983
+ perPage: perPageInput ?? 20,
4984
+ hasMore: false
4985
+ };
4986
+ }
4987
+ const perPage = normalizePerPage(perPageInput, 20);
4988
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
4989
+ const limitValue = perPageInput === false ? total : perPage;
4990
+ const end = perPageInput === false ? total : start + perPage;
4991
+ const result = await this.#client.execute({
4992
+ sql: `SELECT ${buildSelectColumns(TABLE_MCP_SERVER_VERSIONS)} FROM "${TABLE_MCP_SERVER_VERSIONS}" WHERE mcpServerId = ? ORDER BY ${field} ${direction} LIMIT ? OFFSET ?`,
4993
+ args: [mcpServerId, limitValue, start]
4994
+ });
4995
+ const versions = result.rows?.map((row) => this.#parseVersionRow(row)) ?? [];
4996
+ return {
4997
+ versions,
4998
+ total,
4999
+ page,
5000
+ perPage: perPageForResponse,
5001
+ hasMore: end < total
5002
+ };
5003
+ } catch (error) {
5004
+ if (error instanceof MastraError) throw error;
5005
+ throw new MastraError(
5006
+ {
5007
+ id: createStorageErrorId("LIBSQL", "LIST_MCP_SERVER_VERSIONS", "FAILED"),
5008
+ domain: ErrorDomain.STORAGE,
5009
+ category: ErrorCategory.THIRD_PARTY
5010
+ },
5011
+ error
5012
+ );
5013
+ }
5014
+ }
5015
+ async deleteVersion(id) {
5016
+ try {
5017
+ await this.#client.execute({
5018
+ sql: `DELETE FROM "${TABLE_MCP_SERVER_VERSIONS}" WHERE "id" = ?`,
5019
+ args: [id]
5020
+ });
5021
+ } catch (error) {
5022
+ if (error instanceof MastraError) throw error;
5023
+ throw new MastraError(
5024
+ {
5025
+ id: createStorageErrorId("LIBSQL", "DELETE_MCP_SERVER_VERSION", "FAILED"),
5026
+ domain: ErrorDomain.STORAGE,
5027
+ category: ErrorCategory.THIRD_PARTY
5028
+ },
5029
+ error
5030
+ );
5031
+ }
5032
+ }
5033
+ async deleteVersionsByParentId(entityId) {
5034
+ try {
5035
+ await this.#client.execute({
5036
+ sql: `DELETE FROM "${TABLE_MCP_SERVER_VERSIONS}" WHERE "mcpServerId" = ?`,
5037
+ args: [entityId]
5038
+ });
5039
+ } catch (error) {
5040
+ if (error instanceof MastraError) throw error;
5041
+ throw new MastraError(
5042
+ {
5043
+ id: createStorageErrorId("LIBSQL", "DELETE_MCP_SERVER_VERSIONS_BY_SERVER", "FAILED"),
5044
+ domain: ErrorDomain.STORAGE,
5045
+ category: ErrorCategory.THIRD_PARTY
5046
+ },
5047
+ error
5048
+ );
5049
+ }
5050
+ }
5051
+ async countVersions(mcpServerId) {
5052
+ try {
5053
+ const result = await this.#client.execute({
5054
+ sql: `SELECT COUNT(*) as count FROM "${TABLE_MCP_SERVER_VERSIONS}" WHERE mcpServerId = ?`,
5055
+ args: [mcpServerId]
5056
+ });
5057
+ return Number(result.rows?.[0]?.count ?? 0);
5058
+ } catch (error) {
5059
+ if (error instanceof MastraError) throw error;
5060
+ throw new MastraError(
5061
+ {
5062
+ id: createStorageErrorId("LIBSQL", "COUNT_MCP_SERVER_VERSIONS", "FAILED"),
5063
+ domain: ErrorDomain.STORAGE,
5064
+ category: ErrorCategory.THIRD_PARTY
5065
+ },
5066
+ error
5067
+ );
5068
+ }
5069
+ }
5070
+ // ==========================================================================
5071
+ // Private Helpers
5072
+ // ==========================================================================
5073
+ #safeParseJSON(val) {
5074
+ if (val === null || val === void 0) return void 0;
5075
+ if (typeof val === "string") {
5076
+ try {
5077
+ return JSON.parse(val);
5078
+ } catch {
5079
+ return val;
5080
+ }
5081
+ }
5082
+ return val;
5083
+ }
5084
+ #parseMCPServerRow(row) {
5085
+ return {
5086
+ id: row.id,
5087
+ status: row.status ?? "draft",
5088
+ activeVersionId: row.activeVersionId ?? void 0,
5089
+ authorId: row.authorId ?? void 0,
5090
+ metadata: this.#safeParseJSON(row.metadata),
5091
+ createdAt: new Date(row.createdAt),
5092
+ updatedAt: new Date(row.updatedAt)
5093
+ };
5094
+ }
5095
+ #parseVersionRow(row) {
5096
+ return {
5097
+ id: row.id,
5098
+ mcpServerId: row.mcpServerId,
5099
+ versionNumber: Number(row.versionNumber),
5100
+ name: row.name,
5101
+ version: row.version,
5102
+ description: row.description ?? void 0,
5103
+ instructions: row.instructions ?? void 0,
5104
+ repository: this.#safeParseJSON(row.repository),
5105
+ releaseDate: row.releaseDate ?? void 0,
5106
+ isLatest: row.isLatest === null || row.isLatest === void 0 ? void 0 : Boolean(row.isLatest),
5107
+ packageCanonical: row.packageCanonical ?? void 0,
5108
+ tools: this.#safeParseJSON(row.tools),
5109
+ agents: this.#safeParseJSON(row.agents),
5110
+ workflows: this.#safeParseJSON(row.workflows),
5111
+ changedFields: this.#safeParseJSON(row.changedFields),
5112
+ changeMessage: row.changeMessage ?? void 0,
5113
+ createdAt: new Date(row.createdAt)
5114
+ };
5115
+ }
5116
+ };
4633
5117
  var OM_TABLE = "mastra_observational_memory";
4634
5118
  var MemoryLibSQL = class extends MemoryStorage {
4635
5119
  supportsObservationalMemory = true;
@@ -6294,32 +6778,40 @@ var MemoryLibSQL = class extends MemoryStorage {
6294
6778
  const retentionFloor = input.messageTokensThreshold * (1 - input.activationRatio);
6295
6779
  const targetMessageTokens = Math.max(0, input.currentPendingTokens - retentionFloor);
6296
6780
  let cumulativeMessageTokens = 0;
6297
- let bestBoundary = 0;
6298
- let bestBoundaryMessageTokens = 0;
6781
+ let bestOverBoundary = 0;
6782
+ let bestOverTokens = 0;
6783
+ let bestUnderBoundary = 0;
6784
+ let bestUnderTokens = 0;
6299
6785
  for (let i = 0; i < chunks.length; i++) {
6300
6786
  cumulativeMessageTokens += chunks[i].messageTokens ?? 0;
6301
6787
  const boundary = i + 1;
6302
- const isUnder = cumulativeMessageTokens <= targetMessageTokens;
6303
- const bestIsUnder = bestBoundaryMessageTokens <= targetMessageTokens;
6304
- if (bestBoundary === 0) {
6305
- bestBoundary = boundary;
6306
- bestBoundaryMessageTokens = cumulativeMessageTokens;
6307
- } else if (isUnder && !bestIsUnder) {
6308
- bestBoundary = boundary;
6309
- bestBoundaryMessageTokens = cumulativeMessageTokens;
6310
- } else if (isUnder && bestIsUnder) {
6311
- if (cumulativeMessageTokens > bestBoundaryMessageTokens) {
6312
- bestBoundary = boundary;
6313
- bestBoundaryMessageTokens = cumulativeMessageTokens;
6788
+ if (cumulativeMessageTokens >= targetMessageTokens) {
6789
+ if (bestOverBoundary === 0 || cumulativeMessageTokens < bestOverTokens) {
6790
+ bestOverBoundary = boundary;
6791
+ bestOverTokens = cumulativeMessageTokens;
6314
6792
  }
6315
- } else if (!isUnder && !bestIsUnder) {
6316
- if (cumulativeMessageTokens < bestBoundaryMessageTokens) {
6317
- bestBoundary = boundary;
6318
- bestBoundaryMessageTokens = cumulativeMessageTokens;
6793
+ } else {
6794
+ if (cumulativeMessageTokens > bestUnderTokens) {
6795
+ bestUnderBoundary = boundary;
6796
+ bestUnderTokens = cumulativeMessageTokens;
6319
6797
  }
6320
6798
  }
6321
6799
  }
6322
- const chunksToActivate = bestBoundary === 0 ? 1 : bestBoundary;
6800
+ const maxOvershoot = retentionFloor * 0.95;
6801
+ const overshoot = bestOverTokens - targetMessageTokens;
6802
+ const remainingAfterOver = input.currentPendingTokens - bestOverTokens;
6803
+ let chunksToActivate;
6804
+ if (input.forceMaxActivation && bestOverBoundary > 0) {
6805
+ chunksToActivate = bestOverBoundary;
6806
+ } else if (bestOverBoundary > 0 && overshoot <= maxOvershoot && (remainingAfterOver >= 1e3 || retentionFloor === 0)) {
6807
+ chunksToActivate = bestOverBoundary;
6808
+ } else if (bestUnderBoundary > 0) {
6809
+ chunksToActivate = bestUnderBoundary;
6810
+ } else if (bestOverBoundary > 0) {
6811
+ chunksToActivate = bestOverBoundary;
6812
+ } else {
6813
+ chunksToActivate = 1;
6814
+ }
6323
6815
  const activatedChunks = chunks.slice(0, chunksToActivate);
6324
6816
  const remainingChunks = chunks.slice(chunksToActivate);
6325
6817
  const activatedContent = activatedChunks.map((c) => c.observations).join("\n\n");
@@ -6358,6 +6850,7 @@ ${activatedContent}` : activatedContent;
6358
6850
  input.id
6359
6851
  ]
6360
6852
  });
6853
+ const latestChunkHints = activatedChunks[activatedChunks.length - 1];
6361
6854
  return {
6362
6855
  chunksActivated: activatedChunks.length,
6363
6856
  messageTokensActivated: activatedMessageTokens,
@@ -6372,7 +6865,9 @@ ${activatedContent}` : activatedContent;
6372
6865
  observationTokens: c.tokenCount,
6373
6866
  messageCount: c.messageIds.length,
6374
6867
  observations: c.observations
6375
- }))
6868
+ })),
6869
+ suggestedContinuation: latestChunkHints?.suggestedContinuation ?? void 0,
6870
+ currentTask: latestChunkHints?.currentTask ?? void 0
6376
6871
  };
6377
6872
  } catch (error) {
6378
6873
  if (error instanceof MastraError) {
@@ -9651,6 +10146,7 @@ var LibSQLStore = class extends MastraCompositeStore {
9651
10146
  const promptBlocks = new PromptBlocksLibSQL(domainConfig);
9652
10147
  const scorerDefinitions = new ScorerDefinitionsLibSQL(domainConfig);
9653
10148
  const mcpClients = new MCPClientsLibSQL(domainConfig);
10149
+ const mcpServers = new MCPServersLibSQL(domainConfig);
9654
10150
  const workspaces = new WorkspacesLibSQL(domainConfig);
9655
10151
  const skills = new SkillsLibSQL(domainConfig);
9656
10152
  const blobs = new BlobsLibSQL(domainConfig);
@@ -9665,6 +10161,7 @@ var LibSQLStore = class extends MastraCompositeStore {
9665
10161
  promptBlocks,
9666
10162
  scorerDefinitions,
9667
10163
  mcpClients,
10164
+ mcpServers,
9668
10165
  workspaces,
9669
10166
  skills,
9670
10167
  blobs
@@ -9771,6 +10268,6 @@ Example Complex Query:
9771
10268
  ]
9772
10269
  }`;
9773
10270
 
9774
- export { AgentsLibSQL, BlobsLibSQL, DatasetsLibSQL, LibSQLStore as DefaultStorage, ExperimentsLibSQL, LIBSQL_PROMPT, LibSQLStore, LibSQLVector, MCPClientsLibSQL, MemoryLibSQL, ObservabilityLibSQL, PromptBlocksLibSQL, ScorerDefinitionsLibSQL, ScoresLibSQL, SkillsLibSQL, WorkflowsLibSQL, WorkspacesLibSQL };
10271
+ export { AgentsLibSQL, BlobsLibSQL, DatasetsLibSQL, LibSQLStore as DefaultStorage, ExperimentsLibSQL, LIBSQL_PROMPT, LibSQLStore, LibSQLVector, MCPClientsLibSQL, MCPServersLibSQL, MemoryLibSQL, ObservabilityLibSQL, PromptBlocksLibSQL, ScorerDefinitionsLibSQL, ScoresLibSQL, SkillsLibSQL, WorkflowsLibSQL, WorkspacesLibSQL };
9775
10272
  //# sourceMappingURL=index.js.map
9776
10273
  //# sourceMappingURL=index.js.map