"use strict";
/*
 * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.main = main;
const sse_js_1 = require("@modelcontextprotocol/sdk/server/sse.js");
const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
const express_1 = __importDefault(require("express"));
const console_logger_js_1 = require("../../console-logger.js");
const server_js_1 = require("../../server.js");
async function main(flags) {
    flags.env?.forEach(([key, value]) => {
        process.env[key] = value;
    });
    switch (flags.transport) {
        case "stdio":
            await startStdio(flags);
            break;
        case "sse":
            await startSSE(flags);
            break;
        default:
            throw new Error(`Invalid transport: ${flags.transport}`);
    }
}
async function startStdio(flags) {
    const logger = (0, console_logger_js_1.createConsoleLogger)(flags["log-level"]);
    const transport = new stdio_js_1.StdioServerTransport();
    const server = (0, server_js_1.createMCPServer)({
        logger,
        allowedTools: flags.tool,
        scopes: flags.scope,
        security: {
            cloudinaryAuth: flags["api-key"] != null && flags["api-secret"] != null
                ? { apiKey: flags["api-key"], apiSecret: flags["api-secret"] }
                : void 0,
            oauth2: flags.oauth2 ?? "",
        },
        cloudName: flags["cloud-name"],
        serverURL: flags["server-url"],
        serverIdx: flags["server-index"],
        region: flags.region,
        host: flags["api-host"],
    });
    await server.connect(transport);
    const abort = async () => {
        await server.close();
        process.exit(0);
    };
    process.on("SIGTERM", abort);
    process.on("SIGINT", abort);
}
async function startSSE(flags) {
    const logger = (0, console_logger_js_1.createConsoleLogger)(flags["log-level"]);
    const app = (0, express_1.default)();
    const mcpServer = (0, server_js_1.createMCPServer)({
        logger,
        allowedTools: flags.tool,
        scopes: flags.scope,
        security: {
            cloudinaryAuth: flags["api-key"] != null && flags["api-secret"] != null
                ? { apiKey: flags["api-key"], apiSecret: flags["api-secret"] }
                : void 0,
            oauth2: flags.oauth2 ?? "",
        },
        cloudName: flags["cloud-name"],
        serverURL: flags["server-url"],
        serverIdx: flags["server-index"],
        region: flags.region,
        host: flags["api-host"],
    });
    let transport;
    const controller = new AbortController();
    app.get("/sse", async (_req, res) => {
        transport = new sse_js_1.SSEServerTransport("/message", res);
        await mcpServer.connect(transport);
        mcpServer.server.onclose = async () => {
            res.end();
        };
    });
    app.post("/message", async (req, res) => {
        if (!transport) {
            throw new Error("Server transport not initialized");
        }
        await transport.handlePostMessage(req, res);
    });
    const httpServer = app.listen(flags.port, "0.0.0.0", () => {
        const ha = httpServer.address();
        const host = typeof ha === "string" ? ha : `${ha?.address}:${ha?.port}`;
        logger.info("MCP HTTP server started", { host });
    });
    let closing = false;
    controller.signal.addEventListener("abort", async () => {
        if (closing) {
            logger.info("Received second signal. Forcing shutdown.");
            process.exit(1);
        }
        closing = true;
        logger.info("Shutting down MCP server");
        await mcpServer.close();
        logger.info("Shutting down HTTP server");
        const timer = setTimeout(() => {
            logger.info("Forcing shutdown");
            process.exit(1);
        }, 5000);
        httpServer.close(() => {
            clearTimeout(timer);
            logger.info("Graceful shutdown complete");
            process.exit(0);
        });
    });
    const abort = () => controller.abort();
    process.on("SIGTERM", abort);
    process.on("SIGINT", abort);
}
//# sourceMappingURL=impl.js.map