All files / src/mcp/imf lifecycle.ts

100% Statements 12/12
100% Branches 5/5
100% Functions 2/2
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49                                  8x                     3x 2x 2x 2x 1x   1x 1x     2x         8x 1x 1x      
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module MCP/imf/lifecycle
 * @description Singleton lifecycle for the IMF MCP client — extracted from
 * `client.ts` so the main client implementation file stays under 600 LOC.
 *
 * Re-exported from `client.ts` for backward compatibility; callers should
 * continue to import `getIMFMCPClient` / `closeIMFMCPClient` from
 * `'./client.js'`.
 */
 
import type { IMFClientOptions } from './types.js';
import { IMFMCPClient } from './client.js';
 
/** Singleton instance, created lazily by {@link getIMFMCPClient}. */
let imfClientInstance: IMFMCPClient | null = null;
 
/**
 * Get or create the singleton IMF client, validating the base URL on
 * first use. Subsequent calls return the cached instance.
 *
 * @param options - Client options (override env vars and defaults).
 * @returns Connected singleton client.
 * @throws When the base URL is malformed (e.g. missing protocol).
 */
export async function getIMFMCPClient(options: IMFClientOptions = {}): Promise<IMFMCPClient> {
  if (!imfClientInstance) {
    const client = new IMFMCPClient(options);
    try {
      await client.connect();
      imfClientInstance = client;
    } catch (error) {
      imfClientInstance = null;
      throw error;
    }
  }
  return imfClientInstance;
}
 
/** Close and clear the singleton instance (idempotent). */
export async function closeIMFMCPClient(): Promise<void> {
  if (imfClientInstance) {
    imfClientInstance.disconnect();
    imfClientInstance = null;
  }
}