import { toSlug } from './chunk-LII44FTI.js';
import { createPagePaginationSchema, paginationInfoSchema } from './chunk-HT4LP3BO.js';
import { handleError } from './chunk-ONN5EA7E.js';
import { createRoute } from './chunk-OQ5GQJAS.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import z from 'zod';

var storedMCPClientIdPathParams = z.object({
  storedMCPClientId: z.string().describe("Unique identifier for the stored MCP client")
});
var storageOrderBySchema = z.object({
  field: z.enum(["createdAt", "updatedAt"]).optional(),
  direction: z.enum(["ASC", "DESC"]).optional()
});
var listStoredMCPClientsQuerySchema = createPagePaginationSchema(100).extend({
  orderBy: storageOrderBySchema.optional(),
  authorId: z.string().optional().describe("Filter MCP clients by author identifier"),
  metadata: z.record(z.string(), z.unknown()).optional().describe("Filter MCP clients by metadata key-value pairs")
});
var mcpServerConfigSchema = z.object({
  type: z.enum(["stdio", "http"]).describe("Transport type: stdio for local processes, http for remote servers"),
  command: z.string().optional().describe("Command to run (stdio only)"),
  args: z.array(z.string()).optional().describe("Command arguments (stdio only)"),
  env: z.record(z.string(), z.string()).optional().describe("Environment variables (stdio only)"),
  url: z.string().optional().describe("Server URL (http only)"),
  timeout: z.number().optional().describe("Connection timeout in milliseconds")
});
var snapshotConfigSchema = z.object({
  name: z.string().describe("Name of the MCP client"),
  description: z.string().optional().describe("Description of the MCP client"),
  servers: z.record(z.string(), mcpServerConfigSchema).describe("Map of server name to server configuration")
});
var createStoredMCPClientBodySchema = z.object({
  id: z.string().optional().describe("Unique identifier. If not provided, derived from name."),
  authorId: z.string().optional().describe("Author identifier for multi-tenant filtering"),
  metadata: z.record(z.string(), z.unknown()).optional().describe("Additional metadata for the MCP client")
}).merge(snapshotConfigSchema);
var updateStoredMCPClientBodySchema = z.object({
  authorId: z.string().optional(),
  metadata: z.record(z.string(), z.unknown()).optional()
}).partial().merge(snapshotConfigSchema.partial());
var storedMCPClientSchema = z.object({
  id: z.string(),
  status: z.string().describe("MCP client status: draft, published, or archived"),
  activeVersionId: z.string().optional(),
  authorId: z.string().optional(),
  metadata: z.record(z.string(), z.unknown()).optional(),
  createdAt: z.coerce.date(),
  updatedAt: z.coerce.date(),
  name: z.string().describe("Name of the MCP client"),
  description: z.string().optional().describe("Description of the MCP client"),
  servers: z.record(z.string(), mcpServerConfigSchema).describe("Map of server name to server configuration")
});
var listStoredMCPClientsResponseSchema = paginationInfoSchema.extend({
  mcpClients: z.array(storedMCPClientSchema)
});
var getStoredMCPClientResponseSchema = storedMCPClientSchema;
var createStoredMCPClientResponseSchema = storedMCPClientSchema;
var updateStoredMCPClientResponseSchema = z.union([
  z.object({
    id: z.string(),
    status: z.string(),
    activeVersionId: z.string().optional(),
    authorId: z.string().optional(),
    metadata: z.record(z.string(), z.unknown()).optional(),
    createdAt: z.coerce.date(),
    updatedAt: z.coerce.date()
  }),
  storedMCPClientSchema
]);
var deleteStoredMCPClientResponseSchema = z.object({
  success: z.boolean(),
  message: z.string()
});

// src/server/handlers/stored-mcp-clients.ts
var LIST_STORED_MCP_CLIENTS_ROUTE = createRoute({
  method: "GET",
  path: "/stored/mcp-clients",
  responseType: "json",
  queryParamSchema: listStoredMCPClientsQuerySchema,
  responseSchema: listStoredMCPClientsResponseSchema,
  summary: "List stored MCP clients",
  description: "Returns a paginated list of all MCP client configurations stored in the database",
  tags: ["Stored MCP Clients"],
  requiresAuth: true,
  handler: async ({ mastra, page, perPage, orderBy, authorId, metadata }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const mcpClientStore = await storage.getStore("mcpClients");
      if (!mcpClientStore) {
        throw new HTTPException(500, { message: "MCP clients storage domain is not available" });
      }
      const result = await mcpClientStore.listResolved({
        page,
        perPage,
        orderBy,
        authorId,
        metadata
      });
      return result;
    } catch (error) {
      return handleError(error, "Error listing stored MCP clients");
    }
  }
});
var GET_STORED_MCP_CLIENT_ROUTE = createRoute({
  method: "GET",
  path: "/stored/mcp-clients/:storedMCPClientId",
  responseType: "json",
  pathParamSchema: storedMCPClientIdPathParams,
  responseSchema: getStoredMCPClientResponseSchema,
  summary: "Get stored MCP client by ID",
  description: "Returns a specific MCP client from storage by its unique identifier (resolved with active version config)",
  tags: ["Stored MCP Clients"],
  requiresAuth: true,
  handler: async ({ mastra, storedMCPClientId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const mcpClientStore = await storage.getStore("mcpClients");
      if (!mcpClientStore) {
        throw new HTTPException(500, { message: "MCP clients storage domain is not available" });
      }
      const mcpClient = await mcpClientStore.getByIdResolved(storedMCPClientId);
      if (!mcpClient) {
        throw new HTTPException(404, { message: `Stored MCP client with id ${storedMCPClientId} not found` });
      }
      return mcpClient;
    } catch (error) {
      return handleError(error, "Error getting stored MCP client");
    }
  }
});
var CREATE_STORED_MCP_CLIENT_ROUTE = createRoute({
  method: "POST",
  path: "/stored/mcp-clients",
  responseType: "json",
  bodySchema: createStoredMCPClientBodySchema,
  responseSchema: createStoredMCPClientResponseSchema,
  summary: "Create stored MCP client",
  description: "Creates a new MCP client configuration in storage with the provided servers",
  tags: ["Stored MCP Clients"],
  requiresAuth: true,
  handler: async ({ mastra, id: providedId, authorId, metadata, name, description, servers }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const mcpClientStore = await storage.getStore("mcpClients");
      if (!mcpClientStore) {
        throw new HTTPException(500, { message: "MCP clients storage domain is not available" });
      }
      const id = providedId || toSlug(name);
      if (!id) {
        throw new HTTPException(400, {
          message: "Could not derive MCP client ID from name. Please provide an explicit id."
        });
      }
      const existing = await mcpClientStore.getById(id);
      if (existing) {
        throw new HTTPException(409, { message: `MCP client with id ${id} already exists` });
      }
      await mcpClientStore.create({
        mcpClient: {
          id,
          authorId,
          metadata,
          name,
          description,
          servers
        }
      });
      const resolved = await mcpClientStore.getByIdResolved(id);
      if (!resolved) {
        throw new HTTPException(500, { message: "Failed to resolve created MCP client" });
      }
      return resolved;
    } catch (error) {
      return handleError(error, "Error creating stored MCP client");
    }
  }
});
var UPDATE_STORED_MCP_CLIENT_ROUTE = createRoute({
  method: "PATCH",
  path: "/stored/mcp-clients/:storedMCPClientId",
  responseType: "json",
  pathParamSchema: storedMCPClientIdPathParams,
  bodySchema: updateStoredMCPClientBodySchema,
  responseSchema: updateStoredMCPClientResponseSchema,
  summary: "Update stored MCP client",
  description: "Updates an existing MCP client in storage with the provided fields",
  tags: ["Stored MCP Clients"],
  requiresAuth: true,
  handler: async ({
    mastra,
    storedMCPClientId,
    // Metadata-level fields
    authorId,
    metadata,
    // Config fields (snapshot-level)
    name,
    description,
    servers
  }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const mcpClientStore = await storage.getStore("mcpClients");
      if (!mcpClientStore) {
        throw new HTTPException(500, { message: "MCP clients storage domain is not available" });
      }
      const existing = await mcpClientStore.getById(storedMCPClientId);
      if (!existing) {
        throw new HTTPException(404, { message: `Stored MCP client with id ${storedMCPClientId} not found` });
      }
      await mcpClientStore.update({
        id: storedMCPClientId,
        authorId,
        metadata,
        name,
        description,
        servers
      });
      const resolved = await mcpClientStore.getByIdResolved(storedMCPClientId);
      if (!resolved) {
        throw new HTTPException(500, { message: "Failed to resolve updated MCP client" });
      }
      return resolved;
    } catch (error) {
      return handleError(error, "Error updating stored MCP client");
    }
  }
});
var DELETE_STORED_MCP_CLIENT_ROUTE = createRoute({
  method: "DELETE",
  path: "/stored/mcp-clients/:storedMCPClientId",
  responseType: "json",
  pathParamSchema: storedMCPClientIdPathParams,
  responseSchema: deleteStoredMCPClientResponseSchema,
  summary: "Delete stored MCP client",
  description: "Deletes an MCP client from storage by its unique identifier",
  tags: ["Stored MCP Clients"],
  requiresAuth: true,
  handler: async ({ mastra, storedMCPClientId }) => {
    try {
      const storage = mastra.getStorage();
      if (!storage) {
        throw new HTTPException(500, { message: "Storage is not configured" });
      }
      const mcpClientStore = await storage.getStore("mcpClients");
      if (!mcpClientStore) {
        throw new HTTPException(500, { message: "MCP clients storage domain is not available" });
      }
      const existing = await mcpClientStore.getById(storedMCPClientId);
      if (!existing) {
        throw new HTTPException(404, { message: `Stored MCP client with id ${storedMCPClientId} not found` });
      }
      await mcpClientStore.delete(storedMCPClientId);
      return {
        success: true,
        message: `MCP client ${storedMCPClientId} deleted successfully`
      };
    } catch (error) {
      return handleError(error, "Error deleting stored MCP client");
    }
  }
});

export { CREATE_STORED_MCP_CLIENT_ROUTE, DELETE_STORED_MCP_CLIENT_ROUTE, GET_STORED_MCP_CLIENT_ROUTE, LIST_STORED_MCP_CLIENTS_ROUTE, UPDATE_STORED_MCP_CLIENT_ROUTE };
//# sourceMappingURL=chunk-KU3UEWBF.js.map
//# sourceMappingURL=chunk-KU3UEWBF.js.map