"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.McpServerRuntime = void 0;
const log_1 = require("../log");
const log = (0, log_1.createLogger)('mcp/server-runtime');
class McpServerRuntime {
    serverId;
    toolsetName;
    client;
    inFlightCount = 0;
    stopRequested = false;
    closed = false;
    forceKillTimer;
    constructor(params) {
        this.serverId = params.serverId;
        this.toolsetName = params.toolsetName;
        this.client = params.client;
    }
    async callTool(mcpToolName, args) {
        if (this.closed) {
            throw new Error(`MCP server ${this.serverId} is closed`);
        }
        this.inFlightCount++;
        try {
            return await this.client.callTool(mcpToolName, args);
        }
        finally {
            this.inFlightCount--;
            if (this.stopRequested && this.inFlightCount <= 0) {
                await this.closeNow();
            }
        }
    }
    async callToolRaw(mcpToolName, args) {
        if (this.closed) {
            throw new Error(`MCP server ${this.serverId} is closed`);
        }
        this.inFlightCount++;
        try {
            return await this.client.callToolRaw(mcpToolName, args);
        }
        finally {
            this.inFlightCount--;
            if (this.stopRequested && this.inFlightCount <= 0) {
                await this.closeNow();
            }
        }
    }
    requestStop(params) {
        if (this.stopRequested)
            return;
        this.stopRequested = true;
        const forceKillAfterMs = params?.forceKillAfterMs ?? 30_000;
        if (this.inFlightCount <= 0) {
            void this.closeNow();
            return;
        }
        if (!this.forceKillTimer) {
            this.forceKillTimer = setTimeout(() => {
                log.warn(`Force-killing MCP server after timeout`, undefined, { serverId: this.serverId });
                void this.closeNow();
            }, forceKillAfterMs);
        }
    }
    async closeNow() {
        if (this.closed)
            return;
        this.closed = true;
        if (this.forceKillTimer) {
            clearTimeout(this.forceKillTimer);
            this.forceKillTimer = undefined;
        }
        await this.client.close();
    }
}
exports.McpServerRuntime = McpServerRuntime;
