'use strict';

var chunkKD3YOO6V_cjs = require('./chunk-KD3YOO6V.cjs');
var chunkAWQJBTJ4_cjs = require('./chunk-AWQJBTJ4.cjs');
var chunkSUKFO7UM_cjs = require('./chunk-SUKFO7UM.cjs');
var chunk4LVJBXI2_cjs = require('./chunk-4LVJBXI2.cjs');
var chunk64ITUOXI_cjs = require('./chunk-64ITUOXI.cjs');
var z = require('zod');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var z__default = /*#__PURE__*/_interopDefault(z);

var listMCPClientVersionsQuerySchema = chunkKD3YOO6V_cjs.listVersionsQuerySchema;
var compareMCPClientVersionsQuerySchema = chunkKD3YOO6V_cjs.compareVersionsQuerySchema;
var createMCPClientVersionBodySchema = chunkKD3YOO6V_cjs.createVersionBodySchema;
var mcpClientVersionPathParams = z__default.default.object({
  mcpClientId: z__default.default.string().describe("Unique identifier for the stored MCP client")
});
var mcpClientVersionIdPathParams = z__default.default.object({
  mcpClientId: z__default.default.string().describe("Unique identifier for the stored MCP client"),
  versionId: z__default.default.string().describe("Unique identifier for the version (UUID)")
});
var mcpServerConfigSchema = z__default.default.object({
  type: z__default.default.enum(["stdio", "http"]),
  command: z__default.default.string().optional(),
  args: z__default.default.array(z__default.default.string()).optional(),
  env: z__default.default.record(z__default.default.string(), z__default.default.string()).optional(),
  url: z__default.default.string().optional(),
  timeout: z__default.default.number().optional()
});
var mcpClientVersionSchema = z__default.default.object({
  id: z__default.default.string().describe("Unique identifier for the version (UUID)"),
  mcpClientId: z__default.default.string().describe("ID of the MCP client this version belongs to"),
  versionNumber: z__default.default.number().describe("Sequential version number (1, 2, 3, ...)"),
  // Snapshot config fields
  name: z__default.default.string().describe("Name of the MCP client"),
  description: z__default.default.string().optional().describe("Description of the MCP client"),
  servers: z__default.default.record(z__default.default.string(), mcpServerConfigSchema),
  // Version metadata
  changedFields: z__default.default.array(z__default.default.string()).optional().describe("Array of field names that changed from the previous version"),
  changeMessage: z__default.default.string().optional().describe("Optional message describing the changes"),
  createdAt: z__default.default.coerce.date().describe("When this version was created")
});
var listMCPClientVersionsResponseSchema = chunkKD3YOO6V_cjs.createListVersionsResponseSchema(mcpClientVersionSchema);
var getMCPClientVersionResponseSchema = mcpClientVersionSchema;
var createMCPClientVersionResponseSchema = mcpClientVersionSchema.partial().merge(
  z__default.default.object({
    id: z__default.default.string(),
    mcpClientId: z__default.default.string(),
    versionNumber: z__default.default.number(),
    createdAt: z__default.default.coerce.date()
  })
);
var activateMCPClientVersionResponseSchema = chunkKD3YOO6V_cjs.activateVersionResponseSchema;
var restoreMCPClientVersionResponseSchema = mcpClientVersionSchema;
var deleteMCPClientVersionResponseSchema = chunkKD3YOO6V_cjs.deleteVersionResponseSchema;
var compareMCPClientVersionsResponseSchema = chunkKD3YOO6V_cjs.createCompareVersionsResponseSchema(mcpClientVersionSchema);

// src/server/handlers/mcp-client-versions.ts
var LIST_MCP_CLIENT_VERSIONS_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/mcp-clients/:mcpClientId/versions",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: mcpClientVersionPathParams,
  queryParamSchema: listMCPClientVersionsQuerySchema,
  responseSchema: listMCPClientVersionsResponseSchema,
  summary: "List MCP client versions",
  description: "Returns a paginated list of all versions for a stored MCP client",
  tags: ["MCP Client Versions"],
  handler: async ({ mastra, mcpClientId, page, perPage, orderBy }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const mcpClientStore = await storage.getStore("mcpClients");
      if (!mcpClientStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "MCP clients storage domain is not available" });
      }
      const mcpClient = await mcpClientStore.getById(mcpClientId);
      if (!mcpClient) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `MCP client with id ${mcpClientId} not found` });
      }
      const result = await mcpClientStore.listVersions({
        mcpClientId,
        page,
        perPage,
        orderBy
      });
      return result;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error listing MCP client versions");
    }
  }
});
var CREATE_MCP_CLIENT_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "POST",
  path: "/stored/mcp-clients/:mcpClientId/versions",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: mcpClientVersionPathParams,
  bodySchema: createMCPClientVersionBodySchema,
  responseSchema: createMCPClientVersionResponseSchema,
  summary: "Create MCP client version",
  description: "Creates a new version snapshot of the current MCP client configuration",
  tags: ["MCP Client Versions"],
  handler: async ({ mastra, mcpClientId, changeMessage }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const mcpClientStore = await storage.getStore("mcpClients");
      if (!mcpClientStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "MCP clients storage domain is not available" });
      }
      const mcpClient = await mcpClientStore.getById(mcpClientId);
      if (!mcpClient) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `MCP client with id ${mcpClientId} not found` });
      }
      let currentConfig = {};
      if (mcpClient.activeVersionId) {
        const activeVersion = await mcpClientStore.getVersion(mcpClient.activeVersionId);
        if (activeVersion) {
          currentConfig = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
            activeVersion,
            chunkAWQJBTJ4_cjs.MCP_CLIENT_SNAPSHOT_CONFIG_FIELDS
          );
        }
      }
      const latestVersion = await mcpClientStore.getLatestVersion(mcpClientId);
      if (!mcpClient.activeVersionId && latestVersion) {
        currentConfig = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
          latestVersion,
          chunkAWQJBTJ4_cjs.MCP_CLIENT_SNAPSHOT_CONFIG_FIELDS
        );
      }
      const previousConfig = latestVersion ? chunkAWQJBTJ4_cjs.extractConfigFromVersion(
        latestVersion,
        chunkAWQJBTJ4_cjs.MCP_CLIENT_SNAPSHOT_CONFIG_FIELDS
      ) : null;
      const changedFields = chunkAWQJBTJ4_cjs.calculateChangedFields(previousConfig, currentConfig);
      const { versionId } = await chunkAWQJBTJ4_cjs.createVersionWithRetry(
        mcpClientStore,
        mcpClientId,
        "mcpClientId",
        currentConfig,
        changedFields,
        { changeMessage }
      );
      const version = await mcpClientStore.getVersion(versionId);
      if (!version) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to retrieve created version" });
      }
      await chunkAWQJBTJ4_cjs.enforceRetentionLimit(
        mcpClientStore,
        mcpClientId,
        "mcpClientId",
        mcpClient.activeVersionId
      );
      return version;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error creating MCP client version");
    }
  }
});
var GET_MCP_CLIENT_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/mcp-clients/:mcpClientId/versions/:versionId",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: mcpClientVersionIdPathParams,
  responseSchema: getMCPClientVersionResponseSchema,
  summary: "Get MCP client version",
  description: "Returns a specific version of an MCP client by its version ID",
  tags: ["MCP Client Versions"],
  handler: async ({ mastra, mcpClientId, versionId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const mcpClientStore = await storage.getStore("mcpClients");
      if (!mcpClientStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "MCP clients storage domain is not available" });
      }
      const version = await mcpClientStore.getVersion(versionId);
      if (!version) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found` });
      }
      if (version.mcpClientId !== mcpClientId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, {
          message: `Version with id ${versionId} not found for MCP client ${mcpClientId}`
        });
      }
      return version;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error getting MCP client version");
    }
  }
});
var ACTIVATE_MCP_CLIENT_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "POST",
  path: "/stored/mcp-clients/:mcpClientId/versions/:versionId/activate",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: mcpClientVersionIdPathParams,
  responseSchema: activateMCPClientVersionResponseSchema,
  summary: "Activate MCP client version",
  description: "Sets a specific version as the active version for the MCP client",
  tags: ["MCP Client Versions"],
  handler: async ({ mastra, mcpClientId, versionId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const mcpClientStore = await storage.getStore("mcpClients");
      if (!mcpClientStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "MCP clients storage domain is not available" });
      }
      const mcpClient = await mcpClientStore.getById(mcpClientId);
      if (!mcpClient) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `MCP client with id ${mcpClientId} not found` });
      }
      const version = await mcpClientStore.getVersion(versionId);
      if (!version) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found` });
      }
      if (version.mcpClientId !== mcpClientId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, {
          message: `Version with id ${versionId} not found for MCP client ${mcpClientId}`
        });
      }
      await mcpClientStore.update({
        id: mcpClientId,
        activeVersionId: versionId,
        status: "published"
      });
      mastra.getEditor()?.mcp.clearCache(mcpClientId);
      return {
        success: true,
        message: `Version ${version.versionNumber} is now active`,
        activeVersionId: versionId
      };
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error activating MCP client version");
    }
  }
});
var RESTORE_MCP_CLIENT_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "POST",
  path: "/stored/mcp-clients/:mcpClientId/versions/:versionId/restore",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: mcpClientVersionIdPathParams,
  responseSchema: restoreMCPClientVersionResponseSchema,
  summary: "Restore MCP client version",
  description: "Restores the MCP client configuration from a version, creating a new version",
  tags: ["MCP Client Versions"],
  handler: async ({ mastra, mcpClientId, versionId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const mcpClientStore = await storage.getStore("mcpClients");
      if (!mcpClientStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "MCP clients storage domain is not available" });
      }
      const mcpClient = await mcpClientStore.getById(mcpClientId);
      if (!mcpClient) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `MCP client with id ${mcpClientId} not found` });
      }
      const versionToRestore = await mcpClientStore.getVersion(versionId);
      if (!versionToRestore) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found` });
      }
      if (versionToRestore.mcpClientId !== mcpClientId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, {
          message: `Version with id ${versionId} not found for MCP client ${mcpClientId}`
        });
      }
      const restoredConfig = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
        versionToRestore,
        chunkAWQJBTJ4_cjs.MCP_CLIENT_SNAPSHOT_CONFIG_FIELDS
      );
      await mcpClientStore.update({
        id: mcpClientId,
        ...restoredConfig
      });
      const latestVersion = await mcpClientStore.getLatestVersion(mcpClientId);
      const previousConfig = latestVersion ? chunkAWQJBTJ4_cjs.extractConfigFromVersion(
        latestVersion,
        chunkAWQJBTJ4_cjs.MCP_CLIENT_SNAPSHOT_CONFIG_FIELDS
      ) : null;
      const changedFields = chunkAWQJBTJ4_cjs.calculateChangedFields(previousConfig, restoredConfig);
      const { versionId: newVersionId } = await chunkAWQJBTJ4_cjs.createVersionWithRetry(
        mcpClientStore,
        mcpClientId,
        "mcpClientId",
        restoredConfig,
        changedFields,
        {
          changeMessage: `Restored from version ${versionToRestore.versionNumber}`
        }
      );
      const newVersion = await mcpClientStore.getVersion(newVersionId);
      if (!newVersion) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Failed to retrieve created version" });
      }
      await chunkAWQJBTJ4_cjs.enforceRetentionLimit(
        mcpClientStore,
        mcpClientId,
        "mcpClientId",
        mcpClient.activeVersionId
      );
      mastra.getEditor()?.mcp.clearCache(mcpClientId);
      return newVersion;
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error restoring MCP client version");
    }
  }
});
var DELETE_MCP_CLIENT_VERSION_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "DELETE",
  path: "/stored/mcp-clients/:mcpClientId/versions/:versionId",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: mcpClientVersionIdPathParams,
  responseSchema: deleteMCPClientVersionResponseSchema,
  summary: "Delete MCP client version",
  description: "Deletes a specific version (cannot delete the active version)",
  tags: ["MCP Client Versions"],
  handler: async ({ mastra, mcpClientId, versionId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const mcpClientStore = await storage.getStore("mcpClients");
      if (!mcpClientStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "MCP clients storage domain is not available" });
      }
      const mcpClient = await mcpClientStore.getById(mcpClientId);
      if (!mcpClient) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `MCP client with id ${mcpClientId} not found` });
      }
      const version = await mcpClientStore.getVersion(versionId);
      if (!version) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${versionId} not found` });
      }
      if (version.mcpClientId !== mcpClientId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, {
          message: `Version with id ${versionId} not found for MCP client ${mcpClientId}`
        });
      }
      if (mcpClient.activeVersionId === versionId) {
        throw new chunk64ITUOXI_cjs.HTTPException(400, {
          message: "Cannot delete the active version. Activate a different version first."
        });
      }
      await mcpClientStore.deleteVersion(versionId);
      mastra.getEditor()?.mcp.clearCache(mcpClientId);
      return {
        success: true,
        message: `Version ${version.versionNumber} deleted successfully`
      };
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error deleting MCP client version");
    }
  }
});
var COMPARE_MCP_CLIENT_VERSIONS_ROUTE = chunk4LVJBXI2_cjs.createRoute({
  method: "GET",
  path: "/stored/mcp-clients/:mcpClientId/versions/compare",
  requiresAuth: true,
  responseType: "json",
  pathParamSchema: mcpClientVersionPathParams,
  queryParamSchema: compareMCPClientVersionsQuerySchema,
  responseSchema: compareMCPClientVersionsResponseSchema,
  summary: "Compare MCP client versions",
  description: "Compares two versions and returns the differences between them",
  tags: ["MCP Client Versions"],
  handler: async ({ mastra, mcpClientId, from, to }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "Storage is not configured" });
      }
      const mcpClientStore = await storage.getStore("mcpClients");
      if (!mcpClientStore) {
        throw new chunk64ITUOXI_cjs.HTTPException(500, { message: "MCP clients storage domain is not available" });
      }
      const fromVersion = await mcpClientStore.getVersion(from);
      if (!fromVersion) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${from} not found` });
      }
      if (fromVersion.mcpClientId !== mcpClientId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, {
          message: `Version with id ${from} not found for MCP client ${mcpClientId}`
        });
      }
      const toVersion = await mcpClientStore.getVersion(to);
      if (!toVersion) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, { message: `Version with id ${to} not found` });
      }
      if (toVersion.mcpClientId !== mcpClientId) {
        throw new chunk64ITUOXI_cjs.HTTPException(404, {
          message: `Version with id ${to} not found for MCP client ${mcpClientId}`
        });
      }
      const fromConfig = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
        fromVersion,
        chunkAWQJBTJ4_cjs.MCP_CLIENT_SNAPSHOT_CONFIG_FIELDS
      );
      const toConfig = chunkAWQJBTJ4_cjs.extractConfigFromVersion(
        toVersion,
        chunkAWQJBTJ4_cjs.MCP_CLIENT_SNAPSHOT_CONFIG_FIELDS
      );
      const diffs = chunkAWQJBTJ4_cjs.computeVersionDiffs(fromConfig, toConfig);
      return {
        diffs,
        fromVersion,
        toVersion
      };
    } catch (error) {
      return chunkSUKFO7UM_cjs.handleError(error, "Error comparing MCP client versions");
    }
  }
});

exports.ACTIVATE_MCP_CLIENT_VERSION_ROUTE = ACTIVATE_MCP_CLIENT_VERSION_ROUTE;
exports.COMPARE_MCP_CLIENT_VERSIONS_ROUTE = COMPARE_MCP_CLIENT_VERSIONS_ROUTE;
exports.CREATE_MCP_CLIENT_VERSION_ROUTE = CREATE_MCP_CLIENT_VERSION_ROUTE;
exports.DELETE_MCP_CLIENT_VERSION_ROUTE = DELETE_MCP_CLIENT_VERSION_ROUTE;
exports.GET_MCP_CLIENT_VERSION_ROUTE = GET_MCP_CLIENT_VERSION_ROUTE;
exports.LIST_MCP_CLIENT_VERSIONS_ROUTE = LIST_MCP_CLIENT_VERSIONS_ROUTE;
exports.RESTORE_MCP_CLIENT_VERSION_ROUTE = RESTORE_MCP_CLIENT_VERSION_ROUTE;
//# sourceMappingURL=chunk-GPSD5CSR.cjs.map
//# sourceMappingURL=chunk-GPSD5CSR.cjs.map