All files / src/config config.service.ts

100% Statements 54/54
100% Branches 43/43
100% Functions 6/6
100% Lines 52/52

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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 1297x 7x 7x   7x   7x         7x 26x 26x           25x 3x 3x     3x 3x     22x     22x 22x 22x             25x 1x     24x 1x       24x 23x     18x 10x           23x 22x 17x 1x   17x         23x 1x     23x         23x       71x 1x   70x       10x   10x 11x 8x 9x 9x 1x               8x   7x           17x 3x   17x       7x   17x 9x          
import * as fs from 'fs';
import { Agent as HttpsAgent } from 'https';
import * as path from 'path';
 
import axios from 'axios';
 
import { Injectable, Logger } from '@nestjs/common';
 
import { Config, FullConfig, OptionsV2 } from './types';
 
@Injectable()
export class ConfigService {
  private readonly logger = new Logger(ConfigService.name);
  private config: Config | null = null;
 
  async load(configPath: string, insecure = false): Promise<Config> {
    let fullConfig: FullConfig;
 
    // Check if configPath is a URL
    if (configPath.startsWith('http://') || configPath.startsWith('https://')) {
      this.logger.log(`Loading config from URL: ${ configPath }`);
      const axiosOptions = insecure ?
        { httpsAgent: new HttpsAgent({ rejectUnauthorized: false }) } :
        {};
      const response = await axios.get<FullConfig>(configPath, axiosOptions);
      fullConfig = response.data;
    } else {
      // Load from file
      const absolutePath = path.isAbsolute(configPath) ?
        configPath :
        path.join(process.cwd(), configPath);
      this.logger.log(`Loading config from file: ${ absolutePath }`);
      const fileContent = fs.readFileSync(absolutePath, 'utf-8');
      fullConfig = JSON.parse(fileContent);
    }
 
    // Adapt V1 to V2 if needed (placeholder for now)
    // TODO: Implement V1 to V2 adaptation if needed
 
    // Validate and expand environment variables
    if (!fullConfig.mcpProxy) {
      throw new Error('mcpProxy is required');
    }
 
    if (!fullConfig.mcpProxy.options) {
      fullConfig.mcpProxy.options = {};
    }
 
    // Expand environment variables in headers
    if (fullConfig.mcpServers) {
      for (const [ _clientName, clientConfig ] of Object.entries(
        fullConfig.mcpServers
      )) {
        if (clientConfig.headers) {
          this.expandEnvVarsInHeaders(clientConfig.headers);
        }
      }
    }
 
    // Inherit options from mcpProxy to mcpServers
    if (fullConfig.mcpServers) {
      for (const clientConfig of Object.values(fullConfig.mcpServers)) {
        if (!clientConfig.options) {
          clientConfig.options = {};
        }
        this.inheritOptions(fullConfig.mcpProxy.options!, clientConfig.options);
      }
    }
 
    // Set default server type to streamable-http (modern MCP standard)
    if (!fullConfig.mcpProxy.type) {
      fullConfig.mcpProxy.type = 'streamable-http';
    }
 
    this.config = {
      mcpProxy: fullConfig.mcpProxy,
      mcpServers: fullConfig.mcpServers || {}
    };
 
    return this.config;
  }
 
  getConfig(): Config {
    if (!this.config) {
      throw new Error('Config not loaded');
    }
    return this.config;
  }
 
  private expandEnvVarsInHeaders(headers: Record<string, string>): void {
    const envVarPattern = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
 
    for (const [ key, value ] of Object.entries(headers)) {
      if (envVarPattern.test(value)) {
        const expanded = value.replace(envVarPattern, (_m, varName) => {
          const envValue = process.env[varName];
          if (typeof envValue === 'undefined') {
            throw new Error([
              'Environment variable ',
              varName,
              ' referenced in header ',
              key,
              ' is not set'
            ].join(''));
          }
          return envValue;
        });
        headers[key] = expanded;
      }
    }
  }
 
  private inheritOptions(parent: OptionsV2, child: OptionsV2): void {
    if (child.authTokens === undefined && parent.authTokens) {
      child.authTokens = parent.authTokens;
    }
    if (
      child.panicIfInvalid === undefined &&
      parent.panicIfInvalid !== undefined
    ) {
      child.panicIfInvalid = parent.panicIfInvalid;
    }
    if (child.logEnabled === undefined && parent.logEnabled !== undefined) {
      child.logEnabled = parent.logEnabled;
    }
    // NOTE: Redaction is intentionally NOT inherited from mcpProxy options
  }
}