"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const zod_1 = require("zod");
const cliUtil_1 = require("@mablhq-internal/runtime/core/cliUtil");
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 loggingProvider_1 = require("@mablhq-internal/runtime/providers/logging/loggingProvider");
const tools_1 = __importDefault(require("./tools"));
const constants_1 = require("../../constants");
const createMablTestForCurrentWork_1 = require("./prompts/createMablTestForCurrentWork");
const MablMcpContext_1 = require("./contexts/MablMcpContext");
exports.command = 'start [options]';
exports.describe = 'Start the MCP server';
exports.builder = (yargs) => {
    yargs
        .option(constants_1.CommandArgApiKey, {
        alias: constants_1.CommandArgAliases.ApiKey,
        describe: 'API key (found in the mabl web app)',
        type: 'string',
        demand: false,
        hidden: true,
    })
        .example('$0 mcp start', 'Start the MCP server');
};
exports.handler = (0, cliUtil_1.failWrapper)(startServer);
async function startServer(parsed) {
    (0, loggingProvider_1.sendLogsToStdErr)();
    const server = new index_js_1.Server({
        name: 'mabl',
        version: '1.0.0',
    }, {
        capabilities: {
            tools: {},
            prompts: {},
            logging: {
                methods: ['notifications/message'],
            },
        },
    });
    server.setRequestHandler(types_js_1.ListToolsRequestSchema, () => ({
        tools: tools_1.default.map((tool) => ({
            name: tool.schema.name,
            description: tool.schema.description,
            inputSchema: zod_1.z.toJSONSchema(tool.schema.inputSchema),
            outputSchema: tool.schema.outputSchema
                ? zod_1.z.toJSONSchema(tool.schema.outputSchema)
                : undefined,
        })),
    }));
    server.setRequestHandler(types_js_1.SetLevelRequestSchema, () => ({}));
    server.setRequestHandler(types_js_1.ListPromptsRequestSchema, () => ({
        prompts: [createMablTestForCurrentWork_1.createMablTestPrompt],
    }));
    server.setRequestHandler(types_js_1.GetPromptRequestSchema, (request) => {
        const { name } = request.params;
        if (name === createMablTestForCurrentWork_1.createMablTestPrompt.name) {
            return {
                messages: (0, createMablTestForCurrentWork_1.getCreateMablTestMessages)(request.params.arguments || {}),
            };
        }
        throw new Error(`Unknown prompt: ${name}`);
    });
    const context = new MablMcpContext_1.MablMcpContext();
    server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
        const { name } = request.params;
        const tool = tools_1.default.find((t) => t.schema.name === name);
        if (!tool) {
            throw new Error(`Unknown tool: ${name}`);
        }
        try {
            const args = request.params.arguments || {};
            if (!context.isInitialized()) {
                const initResult = await context.initialize(parsed[constants_1.CommandArgApiKey]);
                if (!initResult.success) {
                    return {
                        isError: true,
                        content: [
                            {
                                type: 'text',
                                text: initResult.errorMessage || 'Failed to initialize',
                            },
                        ],
                    };
                }
            }
            const result = await tool.handle(args, context, server);
            return {
                content: result.content,
                structuredContent: result.structuredContent,
                isError: result.isError,
            };
        }
        catch (error) {
            throw error;
        }
    });
    const transport = new stdio_js_1.StdioServerTransport();
    await server.connect(transport);
    console.error('Mabl MCP Server running on stdio');
}
