"use strict";
/**
 * MCP Streamable HTTP endpoint.
 *
 * Exposes long-tail's built-in MCP tools to external clients
 * (Claude Desktop, Cursor, other agents) via the standard MCP
 * streamable-http transport protocol.
 *
 * Stateless mode — each POST creates a fresh server+transport pair.
 * Auth via Bearer token (JWT or bot API key) in the Authorization header.
 *
 * Mount at /mcp:
 *   POST /mcp  → JSON-RPC messages (initialize, tools/list, tools/call)
 *   GET  /mcp  → 405 (no SSE in stateless mode)
 *   DELETE /mcp → 405 (no sessions in stateless mode)
 */
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
const auth_1 = require("../modules/auth");
const logger_1 = require("../lib/logger");
const external_server_1 = require("../services/mcp/external-server");
const exposure_1 = require("../services/mcp/exposure");
const router = (0, express_1.Router)();
// All MCP endpoint requests require authentication
router.use(auth_1.requireAuth);
// POST /mcp — JSON-RPC messages
router.post('/', async (req, res) => {
    try {
        const exposure = (0, exposure_1.getExposureConfig)();
        const callerScopes = req.auth?.scopes;
        const server = await (0, external_server_1.createUnifiedMcpServer)(exposure, callerScopes);
        const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({
            sessionIdGenerator: undefined, // stateless
        });
        res.on('close', () => {
            transport.close().catch(() => { });
            server.close().catch(() => { });
        });
        await server.connect(transport);
        await transport.handleRequest(req, res, req.body);
    }
    catch (err) {
        logger_1.loggerRegistry.error(`[lt-mcp:endpoint] error: ${err.message}`);
        if (!res.headersSent) {
            res.status(500).json({
                jsonrpc: '2.0',
                error: { code: -32603, message: 'Internal server error' },
                id: null,
            });
        }
    }
});
// GET /mcp — SSE stream (not supported in stateless mode)
router.get('/', (_req, res) => {
    res.status(405).json({
        jsonrpc: '2.0',
        error: { code: -32000, message: 'Method not allowed. Use POST for stateless requests.' },
        id: null,
    });
});
// DELETE /mcp — session close (not supported in stateless mode)
router.delete('/', (_req, res) => {
    res.status(405).json({
        jsonrpc: '2.0',
        error: { code: -32000, message: 'Method not allowed. Stateless mode has no sessions.' },
        id: null,
    });
});
exports.default = router;
