/*
 * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.
 */
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import express from "express";
import { createConsoleLogger, } from "../../console-logger.js";
import { createMCPServer } from "../../server.js";
import { buildAnnotationFilter } from "../../tools.js";
import { buildSDK } from "../../tools.js";
import { landingPageExpress } from "../../../landing-page.js";
export async function main(flags) {
    flags.env?.forEach(([key, value]) => {
        process.env[key] = value;
    });
    await startStreamableHTTP(flags);
}
async function startStreamableHTTP(cliFlags) {
    const logger = createConsoleLogger(cliFlags["log-level"]);
    const app = express();
    // Enable CORS for cross-origin requests
    app.use((req, res, next) => {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        res.header("Access-Control-Allow-Headers", "*");
        if (req.method === "OPTIONS") {
            res.sendStatus(204);
            return;
        }
        next();
    });
    app.use(express.json());
    app.post("/mcp", async (req, res) => {
        const headers = new Headers();
        for (const [key, value] of Object.entries(req.headers)) {
            if (Array.isArray(value)) {
                for (const v of value)
                    headers.append(key, v);
            }
            else if (value !== undefined) {
                headers.set(key, value);
            }
        }
        const transport = new StreamableHTTPServerTransport({});
        const { server: mcpServer } = createMCPServer({
            logger,
            allowedTools: cliFlags.tool,
            dynamic: cliFlags.mode === "dynamic",
            annotationFilter: buildAnnotationFilter(cliFlags["tool-annotations"]),
            scopes: cliFlags.scope,
            serverURL: cliFlags["server-url"],
            getSDK: () => buildSDK(headers, cliFlags, cliFlags["disable-static-auth"], logger),
            cloud_name: cliFlags["cloud-name"],
            serverIdx: cliFlags["server-index"],
            region: cliFlags.region,
            host: cliFlags["api-host"],
        });
        mcpServer.server.onerror = (error) => {
            logger.error("MCP protocol error", {
                error: error instanceof Error ? error.message : String(error),
                stack: error instanceof Error ? error.stack : undefined,
            });
        };
        await mcpServer.connect(transport);
        await transport.handleRequest(req, res, req.body);
    });
    app.get("/", landingPageExpress);
    const httpServer = app.listen(cliFlags.port, "0.0.0.0", () => {
        const ha = httpServer.address();
        const host = typeof ha === "string" ? ha : `${ha?.address}:${ha?.port}`;
        logger.info("MCP Streamable HTTP server started", { host });
    });
    const shutdown = () => {
        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);
        });
    };
    process.on("SIGTERM", shutdown);
    process.on("SIGINT", shutdown);
}
//# sourceMappingURL=impl.js.map