import { listMcpServersResponseSchema, listMcpServersQuerySchema, serverDetailSchema, getMcpServerDetailQuerySchema, mcpServerDetailPathParams, listMcpServerToolsResponseSchema, mcpServerIdPathParams, mcpToolInfoSchema, mcpServerToolPathParams, executeToolResponseSchema, executeToolBodySchema, listResourcesResponseSchema, mcpServerResourcePathParams, readResourceResponseSchema, readResourceBodySchema } from './chunk-356JZOB2.js';
import { createRoute } from './chunk-PIKPS6Q6.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import { __export } from './chunk-PR4QN5HX.js';

// 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_RESOURCES_ROUTE: () => LIST_MCP_SERVER_RESOURCES_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,
  READ_MCP_SERVER_RESOURCE_ROUTE: () => READ_MCP_SERVER_RESOURCE_ROUTE
});
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, requestContext }) => {
    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 await server.getToolListInfo(requestContext);
  }
});
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 = await 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,
    requestContext
  }) => {
    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, { requestContext });
    return { result };
  }
});
var LIST_MCP_SERVER_RESOURCES_ROUTE = createRoute({
  method: "GET",
  path: "/mcp/:serverId/resources",
  responseType: "json",
  pathParamSchema: mcpServerResourcePathParams,
  responseSchema: listResourcesResponseSchema,
  summary: "List MCP server resources",
  description: "Returns a list of resources available on the MCP server, including ui:// app resources",
  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.listResources !== "function") {
      return { resources: [] };
    }
    return server.listResources();
  }
});
var READ_MCP_SERVER_RESOURCE_ROUTE = createRoute({
  method: "POST",
  path: "/mcp/:serverId/resources/read",
  responseType: "json",
  pathParamSchema: mcpServerResourcePathParams,
  bodySchema: readResourceBodySchema,
  responseSchema: readResourceResponseSchema,
  summary: "Read MCP server resource content",
  description: "Reads the content of a resource by URI, used for rendering MCP App ui:// resources",
  tags: ["MCP"],
  requiresAuth: true,
  handler: async ({ mastra, serverId, uri }) => {
    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.readResource !== "function") {
      throw new HTTPException(501, { message: `Server '${serverId}' does not support reading resources` });
    }
    try {
      return await server.readResource(uri);
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      if (message.includes("not found") || message.includes("not configured")) {
        throw new HTTPException(404, { message: `Resource '${uri}' not found on server '${serverId}'` });
      }
      throw error;
    }
  }
});
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_RESOURCES_ROUTE, LIST_MCP_SERVER_TOOLS_ROUTE, MCP_HTTP_TRANSPORT_ROUTE, MCP_SSE_MESSAGES_ROUTE, MCP_SSE_TRANSPORT_ROUTE, READ_MCP_SERVER_RESOURCE_ROUTE, mcp_exports };
//# sourceMappingURL=chunk-3VNAOZ3S.js.map
//# sourceMappingURL=chunk-3VNAOZ3S.js.map