import { createCombinedPaginationSchema } from './chunk-HT4LP3BO.js';
import { createRoute } from './chunk-D5VCL56B.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import { __export } from './chunk-PR4QN5HX.js';
import { z } from 'zod';

// src/server/handlers/mcp.ts
var mcp_exports = {};
__export(mcp_exports, {
  EXECUTE_MCP_SERVER_TOOL_ROUTE: () => EXECUTE_MCP_SERVER_TOOL_ROUTE,
  GET_MCP_SERVER_DETAIL_ROUTE: () => GET_MCP_SERVER_DETAIL_ROUTE,
  GET_MCP_SERVER_TOOL_DETAIL_ROUTE: () => GET_MCP_SERVER_TOOL_DETAIL_ROUTE,
  LIST_MCP_SERVERS_ROUTE: () => LIST_MCP_SERVERS_ROUTE,
  LIST_MCP_SERVER_TOOLS_ROUTE: () => LIST_MCP_SERVER_TOOLS_ROUTE,
  MCP_HTTP_TRANSPORT_ROUTE: () => MCP_HTTP_TRANSPORT_ROUTE,
  MCP_SSE_MESSAGES_ROUTE: () => MCP_SSE_MESSAGES_ROUTE,
  MCP_SSE_TRANSPORT_ROUTE: () => MCP_SSE_TRANSPORT_ROUTE
});
var mcpServerIdPathParams = z.object({
  serverId: z.string().describe("MCP server ID")
});
var mcpServerDetailPathParams = z.object({
  id: z.string().describe("MCP server ID")
});
var mcpServerToolPathParams = z.object({
  serverId: z.string().describe("MCP server ID"),
  toolId: z.string().describe("Tool ID")
});
var executeToolBodySchema = z.object({
  data: z.unknown().optional()
});
var listMcpServersQuerySchema = createCombinedPaginationSchema();
var getMcpServerDetailQuerySchema = z.object({
  version: z.string().optional()
});
var versionDetailSchema = z.object({
  version: z.string(),
  release_date: z.string(),
  is_latest: z.boolean()
});
var serverInfoSchema = z.object({
  id: z.string(),
  name: z.string(),
  version_detail: versionDetailSchema
});
var listMcpServersResponseSchema = z.object({
  servers: z.array(serverInfoSchema),
  total_count: z.number(),
  next: z.string().nullable()
});
var serverDetailSchema = z.object({
  id: z.string(),
  name: z.string(),
  description: z.string().optional(),
  version_detail: versionDetailSchema,
  package_canonical: z.string().optional(),
  packages: z.array(z.unknown()).optional(),
  remotes: z.array(z.unknown()).optional()
});
var mcpToolInfoSchema = z.object({
  name: z.string(),
  description: z.string().optional(),
  inputSchema: z.unknown(),
  outputSchema: z.unknown().optional(),
  toolType: z.string().optional()
});
var listMcpServerToolsResponseSchema = z.object({
  tools: z.array(mcpToolInfoSchema)
});
var executeToolResponseSchema = z.object({
  result: z.unknown()
});
z.object({
  jsonrpc: z.literal("2.0"),
  error: z.object({
    code: z.number(),
    message: z.string()
  }),
  id: z.null()
});

// src/server/handlers/mcp.ts
var LIST_MCP_SERVERS_ROUTE = createRoute({
  method: "GET",
  path: "/mcp/v0/servers",
  responseType: "json",
  queryParamSchema: listMcpServersQuerySchema,
  responseSchema: listMcpServersResponseSchema,
  summary: "List MCP servers",
  description: "Returns a list of registered MCP servers with pagination support",
  tags: ["MCP"],
  requiresAuth: true,
  handler: async ({
    mastra,
    routePrefix,
    page,
    perPage,
    limit,
    offset
  }) => {
    if (!mastra || typeof mastra.listMCPServers !== "function") {
      throw new HTTPException(500, { message: "Mastra instance or listMCPServers method not available" });
    }
    const servers = mastra.listMCPServers();
    if (!servers) {
      return { servers: [], total_count: 0, next: null };
    }
    const serverList = Object.values(servers);
    const totalCount = serverList.length;
    const useLegacyFormat = (limit !== void 0 || offset !== void 0) && page === void 0 && perPage === void 0;
    const finalPerPage = perPage ?? limit;
    let finalPage = page;
    if (finalPage === void 0 && offset !== void 0 && finalPerPage !== void 0 && finalPerPage > 0) {
      finalPage = Math.floor(offset / finalPerPage);
    }
    const actualOffset = finalPage !== void 0 && finalPerPage !== void 0 ? finalPage * finalPerPage : 0;
    let paginatedServers = serverList;
    let nextUrl = null;
    if (finalPerPage !== void 0) {
      paginatedServers = serverList.slice(actualOffset, actualOffset + finalPerPage);
      if (actualOffset + finalPerPage < totalCount) {
        const nextPage = (finalPage ?? 0) + 1;
        const prefix = routePrefix ?? "";
        if (useLegacyFormat) {
          const nextOffset = actualOffset + finalPerPage;
          nextUrl = `${prefix}/mcp/v0/servers?limit=${finalPerPage}&offset=${nextOffset}`;
        } else {
          nextUrl = `${prefix}/mcp/v0/servers?perPage=${finalPerPage}&page=${nextPage}`;
        }
      }
    }
    const serverInfoList = paginatedServers.map((server) => server.getServerInfo());
    return {
      servers: serverInfoList,
      total_count: totalCount,
      next: nextUrl
    };
  }
});
var GET_MCP_SERVER_DETAIL_ROUTE = createRoute({
  method: "GET",
  path: "/mcp/v0/servers/:id",
  responseType: "json",
  pathParamSchema: mcpServerDetailPathParams,
  queryParamSchema: getMcpServerDetailQuerySchema,
  responseSchema: serverDetailSchema,
  summary: "Get MCP server details",
  description: "Returns detailed information about a specific MCP server",
  tags: ["MCP"],
  requiresAuth: true,
  handler: async ({ mastra, id, version }) => {
    if (!mastra || typeof mastra.getMCPServerById !== "function") {
      throw new HTTPException(500, { message: "Mastra instance or getMCPServerById method not available" });
    }
    const server = mastra.getMCPServerById(id);
    if (!server) {
      throw new HTTPException(404, { message: `MCP server with ID '${id}' not found` });
    }
    const serverDetail = server.getServerDetail();
    if (version && serverDetail.version_detail.version !== version) {
      throw new HTTPException(404, {
        message: `MCP server with ID '${id}' found, but not version '${version}'. Available version: ${serverDetail.version_detail.version}`
      });
    }
    return serverDetail;
  }
});
var LIST_MCP_SERVER_TOOLS_ROUTE = createRoute({
  method: "GET",
  path: "/mcp/:serverId/tools",
  responseType: "json",
  pathParamSchema: mcpServerIdPathParams,
  responseSchema: listMcpServerToolsResponseSchema,
  summary: "List MCP server tools",
  description: "Returns a list of tools available on the specified MCP server",
  tags: ["MCP"],
  requiresAuth: true,
  handler: async ({ mastra, serverId }) => {
    if (!mastra || typeof mastra.getMCPServerById !== "function") {
      throw new HTTPException(500, { message: "Mastra instance or getMCPServerById method not available" });
    }
    const server = mastra.getMCPServerById(serverId);
    if (!server) {
      throw new HTTPException(404, { message: `MCP server with ID '${serverId}' not found` });
    }
    if (typeof server.getToolListInfo !== "function") {
      throw new HTTPException(501, { message: `Server '${serverId}' cannot list tools in this way.` });
    }
    return server.getToolListInfo();
  }
});
var GET_MCP_SERVER_TOOL_DETAIL_ROUTE = createRoute({
  method: "GET",
  path: "/mcp/:serverId/tools/:toolId",
  responseType: "json",
  pathParamSchema: mcpServerToolPathParams,
  responseSchema: mcpToolInfoSchema,
  summary: "Get MCP server tool details",
  description: "Returns detailed information about a specific tool on the MCP server",
  tags: ["MCP"],
  requiresAuth: true,
  handler: async ({ mastra, serverId, toolId }) => {
    if (!mastra || typeof mastra.getMCPServerById !== "function") {
      throw new HTTPException(500, { message: "Mastra instance or getMCPServerById method not available" });
    }
    const server = mastra.getMCPServerById(serverId);
    if (!server) {
      throw new HTTPException(404, { message: `MCP server with ID '${serverId}' not found` });
    }
    if (typeof server.getToolInfo !== "function") {
      throw new HTTPException(501, { message: `Server '${serverId}' cannot provide tool details in this way.` });
    }
    const toolInfo = server.getToolInfo(toolId);
    if (!toolInfo) {
      throw new HTTPException(404, { message: `Tool with ID '${toolId}' not found on MCP server '${serverId}'` });
    }
    return toolInfo;
  }
});
var EXECUTE_MCP_SERVER_TOOL_ROUTE = createRoute({
  method: "POST",
  path: "/mcp/:serverId/tools/:toolId/execute",
  responseType: "json",
  pathParamSchema: mcpServerToolPathParams,
  bodySchema: executeToolBodySchema,
  responseSchema: executeToolResponseSchema,
  summary: "Execute MCP server tool",
  description: "Executes a tool on the specified MCP server with the provided arguments",
  tags: ["MCP"],
  requiresAuth: true,
  handler: async ({
    mastra,
    serverId,
    toolId,
    data
  }) => {
    if (!mastra || typeof mastra.getMCPServerById !== "function") {
      throw new HTTPException(500, { message: "Mastra instance or getMCPServerById method not available" });
    }
    const server = mastra.getMCPServerById(serverId);
    if (!server) {
      throw new HTTPException(404, { message: `MCP server with ID '${serverId}' not found` });
    }
    if (typeof server.executeTool !== "function") {
      throw new HTTPException(501, { message: `Server '${serverId}' cannot execute tools in this way.` });
    }
    const result = await server.executeTool(toolId, data);
    return { result };
  }
});
var MCP_HTTP_TRANSPORT_ROUTE = createRoute({
  method: "ALL",
  path: "/mcp/:serverId/mcp",
  responseType: "mcp-http",
  pathParamSchema: mcpServerIdPathParams,
  summary: "MCP HTTP Transport",
  description: "Streamable HTTP transport endpoint for MCP protocol communication",
  tags: ["MCP"],
  requiresAuth: true,
  handler: async ({ mastra, serverId }) => {
    if (!mastra || typeof mastra.getMCPServerById !== "function") {
      throw new HTTPException(500, { message: "Mastra instance or getMCPServerById method not available" });
    }
    const server = mastra.getMCPServerById(serverId);
    if (!server) {
      throw new HTTPException(404, { message: `MCP server '${serverId}' not found` });
    }
    return {
      server,
      httpPath: `/mcp/${serverId}/mcp`
    };
  }
});
var MCP_SSE_TRANSPORT_ROUTE = createRoute({
  method: "ALL",
  path: "/mcp/:serverId/sse",
  responseType: "mcp-sse",
  pathParamSchema: mcpServerIdPathParams,
  summary: "MCP SSE Transport",
  description: "SSE transport endpoint for MCP protocol communication",
  tags: ["MCP"],
  requiresAuth: true,
  handler: async ({ mastra, serverId }) => {
    if (!mastra || typeof mastra.getMCPServerById !== "function") {
      throw new HTTPException(500, { message: "Mastra instance or getMCPServerById method not available" });
    }
    const server = mastra.getMCPServerById(serverId);
    if (!server) {
      throw new HTTPException(404, { message: `MCP server '${serverId}' not found` });
    }
    return {
      server,
      ssePath: `/mcp/${serverId}/sse`,
      messagePath: `/mcp/${serverId}/messages`
    };
  }
});
var MCP_SSE_MESSAGES_ROUTE = createRoute({
  method: "POST",
  path: "/mcp/:serverId/messages",
  responseType: "mcp-sse",
  pathParamSchema: mcpServerIdPathParams,
  summary: "MCP SSE Messages",
  description: "Message endpoint for SSE transport (posts messages to active SSE streams)",
  tags: ["MCP"],
  requiresAuth: true,
  handler: MCP_SSE_TRANSPORT_ROUTE.handler
});

export { EXECUTE_MCP_SERVER_TOOL_ROUTE, GET_MCP_SERVER_DETAIL_ROUTE, GET_MCP_SERVER_TOOL_DETAIL_ROUTE, LIST_MCP_SERVERS_ROUTE, LIST_MCP_SERVER_TOOLS_ROUTE, MCP_HTTP_TRANSPORT_ROUTE, MCP_SSE_MESSAGES_ROUTE, MCP_SSE_TRANSPORT_ROUTE, mcp_exports };
//# sourceMappingURL=chunk-XUSAKRLX.js.map
//# sourceMappingURL=chunk-XUSAKRLX.js.map