"use strict";
// =============================================================================
// Vibn Coolify MCP Server
//
// Exposes the Coolify tools from src/tools/coolify-api.ts over the Model Context
// Protocol via stdio. Same security guardrails, same code path as the in-process
// agent runner — just accessible to any MCP-speaking client (Goose,
// Claude Code, Cursor, future harnesses).
//
// Launch:
//   COOLIFY_API_URL=https://coolify.vibnai.com COOLIFY_API_TOKEN=... \
//   node dist/mcp/coolify-server.js
//
// The server speaks the MCP stdio transport on its stdin/stdout. Any logs go to
// stderr so they don't corrupt the protocol stream.
// =============================================================================
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const index_js_1 = require("@modelcontextprotocol/sdk/server/index.js");
const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
const api = __importStar(require("../tools/coolify-api"));
// ---------------------------------------------------------------------------
// Config — single source of truth, loaded once at startup
// ---------------------------------------------------------------------------
function loadConfig() {
    const apiUrl = process.env.COOLIFY_API_URL;
    const apiToken = process.env.COOLIFY_API_TOKEN;
    if (!apiUrl)
        throw new Error('COOLIFY_API_URL env var is required');
    if (!apiToken)
        throw new Error('COOLIFY_API_TOKEN env var is required');
    return { apiUrl, apiToken };
}
// ---------------------------------------------------------------------------
// Tool surface — names, descriptions, and JSON Schema kept byte-identical to
// the in-process registrations in tools/coolify.ts so callers get the same
// behavior regardless of transport.
// ---------------------------------------------------------------------------
const TOOL_DEFINITIONS = [
    {
        name: 'coolify_list_projects',
        description: 'List all projects in the Coolify instance. Returns project names and UUIDs.',
        inputSchema: { type: 'object', properties: {} },
    },
    {
        name: 'coolify_list_applications',
        description: 'List applications in a Coolify project.',
        inputSchema: {
            type: 'object',
            properties: {
                project_uuid: { type: 'string', description: 'Project UUID from coolify_list_projects' },
            },
            required: ['project_uuid'],
        },
    },
    {
        name: 'coolify_deploy',
        description: 'Trigger a deployment for a Coolify application.',
        inputSchema: {
            type: 'object',
            properties: {
                application_uuid: { type: 'string', description: 'Application UUID to deploy' },
            },
            required: ['application_uuid'],
        },
    },
    {
        name: 'coolify_get_logs',
        description: 'Get recent deployment logs for a Coolify application.',
        inputSchema: {
            type: 'object',
            properties: {
                application_uuid: { type: 'string', description: 'Application UUID' },
            },
            required: ['application_uuid'],
        },
    },
    {
        name: 'list_all_apps',
        description: 'List all Coolify applications across all projects with their status (running/stopped/error) and domain.',
        inputSchema: { type: 'object', properties: {} },
    },
    {
        name: 'get_app_status',
        description: 'Get the current deployment status and recent logs for a specific Coolify application by name or UUID.',
        inputSchema: {
            type: 'object',
            properties: {
                app_name: { type: 'string', description: 'Application name (e.g. "vibn-frontend") or UUID' },
            },
            required: ['app_name'],
        },
    },
    {
        name: 'deploy_app',
        description: 'Trigger a Coolify deployment for an app by name. Use after an agent commits code.',
        inputSchema: {
            type: 'object',
            properties: {
                app_name: { type: 'string', description: 'Application name (e.g. "vibn-frontend")' },
            },
            required: ['app_name'],
        },
    },
];
// ---------------------------------------------------------------------------
// Dispatch
// ---------------------------------------------------------------------------
async function dispatch(cfg, name, args) {
    switch (name) {
        case 'coolify_list_projects':
            return api.listProjects(cfg);
        case 'coolify_list_applications':
            return api.listApplications(cfg, String(args.project_uuid));
        case 'coolify_deploy':
            return api.deploy(cfg, String(args.application_uuid));
        case 'coolify_get_logs':
            return api.getLogs(cfg, String(args.application_uuid));
        case 'list_all_apps':
            return api.listAllApps(cfg);
        case 'get_app_status':
            return api.getAppStatus(cfg, String(args.app_name));
        case 'deploy_app':
            return api.deployApp(cfg, String(args.app_name));
        default:
            throw new Error(`Unknown tool: ${name}`);
    }
}
// ---------------------------------------------------------------------------
// Server
// ---------------------------------------------------------------------------
function buildServer(cfg) {
    const server = new index_js_1.Server({ name: 'vibn-coolify', version: '0.1.0' }, { capabilities: { tools: {} } });
    server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
        tools: TOOL_DEFINITIONS.map(t => ({ ...t })),
    }));
    server.setRequestHandler(types_js_1.CallToolRequestSchema, async (req) => {
        const { name, arguments: args = {} } = req.params;
        try {
            const result = await dispatch(cfg, name, args);
            const text = typeof result === 'string' ? result : JSON.stringify(result);
            return { content: [{ type: 'text', text }] };
        }
        catch (err) {
            const message = err instanceof Error ? err.message : String(err);
            return {
                content: [{ type: 'text', text: JSON.stringify({ error: message }) }],
                isError: true,
            };
        }
    });
    return server;
}
async function main() {
    const cfg = loadConfig();
    const server = buildServer(cfg);
    const transport = new stdio_js_1.StdioServerTransport();
    await server.connect(transport);
    // stderr so we don't corrupt the stdio MCP stream
    console.error(`[vibn-coolify-mcp] ready — ${TOOL_DEFINITIONS.length} tools exposed (coolify=${cfg.apiUrl})`);
}
main().catch((err) => {
    console.error('[vibn-coolify-mcp] fatal:', err instanceof Error ? err.stack : err);
    process.exit(1);
});
