All files / src main.ts

100% Statements 74/74
81.25% Branches 39/48
100% Functions 2/2
100% Lines 74/74

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 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202    27x 27x 27x 27x 27x 27x                                     27x     27x 2x 2x 1x 1x   1x 1x 1x         27x     27x 12x 12x             11x   10x 1x 1x     10x                 1x     1x 1x 1x         27x   4x 4x 3x 3x 2x         1x       3x       1x                   1x 1x 1x   23x   2x 2x 1x 1x           1x 1x       21x 21x 20x 2x 1x         1x       1x 1x 1x         27x 26x 26x 22x 2x 2x                           4x 4x         27x   10x     10x 10x 10x     10x                   27x     27x 2x 2x    
 
 
import { startServer } from "./server";
import { logger } from "./logger";
import { tryApplyProfileFromEnv, findProjectConfig, getProjectConfigSummary } from "./profiles";
import { parseCliArgs, displayProjectConfig } from "./cli-utils";
import { autoDiscover, formatDiscoveryResult, AutoDiscoveryResult } from "./discovery";
import { extractNamespaceFromPath } from "./utils/namespace";
 
/**
 * Configuration priority (highest to lowest):
 * 1. --profile CLI argument - selects user profile (host, auth)
 * 2. Project config files (.gitlab-mcp/) - adds restrictions and tool selection
 * 3. Auto-discovered profile from git remote - fallback profile selection
 *
 * Note: Project config (preset.yaml, profile.yaml) ADDS restrictions on top
 * of the selected profile - it doesn't replace the profile selection.
 *
 * When --auto detects a profile but --profile or project config specifies
 * a different one, a warning is logged.
 */
 
/**
 * Main entry point
 */
async function main(): Promise<void> {
  const cliArgs = parseCliArgs();
 
  // Handle --show-project-config flag (display and exit)
  if (cliArgs.showProjectConfig) {
    try {
      const projectConfig = await findProjectConfig(process.cwd());
      displayProjectConfig(projectConfig);
      process.exit(0);
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      logger.error({ error: message }, "Failed to load project config");
      process.exit(1);
    }
  }
 
  // Track configuration sources
  let autoDiscoveryResult: AutoDiscoveryResult | null = null;
 
  // Step 1: Run auto-discovery if --auto flag is set (gather info, don't apply yet)
  if (cliArgs.auto) {
    try {
      autoDiscoveryResult = await autoDiscover({
        repoPath: cliArgs.cwd,
        remoteName: cliArgs.remoteName,
        noProjectConfig: true, // We'll handle project config separately for priority
        dryRun: cliArgs.dryRun,
      });
 
      if (autoDiscoveryResult) {
        // If dry-run, display results and exit
        if (cliArgs.dryRun) {
          console.log(formatDiscoveryResult(autoDiscoveryResult));
          process.exit(0);
        }
 
        logger.info(
          {
            host: autoDiscoveryResult.host,
            project: autoDiscoveryResult.projectPath,
            profile: autoDiscoveryResult.matchedProfile?.profileName,
          },
          "Auto-discovery detected GitLab configuration"
        );
      } else {
        logger.warn("Auto-discovery failed: not in a git repository or no remote found");
      }
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      logger.error({ error: message }, "Auto-discovery failed");
      process.exit(1);
    }
  }
 
  // Step 2: Apply profile (priority: --profile > auto-discovered)
  if (cliArgs.profileName) {
    // CLI profile has highest priority
    try {
      const result = await tryApplyProfileFromEnv(cliArgs.profileName);
      Eif (result) {
        if ("profileName" in result) {
          logger.info(
            { profile: result.profileName, host: result.host },
            "Using CLI-specified profile"
          );
        } else {
          logger.info({ preset: result.presetName }, "Using CLI-specified preset");
        }
 
        // Warn if auto-discovery found a different profile
        if (
          autoDiscoveryResult?.matchedProfile &&
          autoDiscoveryResult.matchedProfile.profileName !== cliArgs.profileName
        ) {
          logger.warn(
            {
              cliProfile: cliArgs.profileName,
              autoProfile: autoDiscoveryResult.matchedProfile.profileName,
            },
            "Auto-discovered profile ignored: --profile takes precedence"
          );
        }
      }
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      logger.error({ error: message }, "Failed to load profile");
      process.exit(1);
    }
  } else if (autoDiscoveryResult?.matchedProfile) {
    // Auto-discovered profile is fallback
    try {
      const result = await tryApplyProfileFromEnv(autoDiscoveryResult.matchedProfile.profileName);
      Eif (result && "profileName" in result) {
        logger.info(
          { profile: result.profileName, host: result.host },
          "Using auto-discovered profile"
        );
      }
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      logger.warn({ error: message }, "Failed to apply auto-discovered profile");
    }
  } else {
    // No CLI profile and no auto-discovery - try default from env
    try {
      const result = await tryApplyProfileFromEnv();
      if (result) {
        if ("profileName" in result) {
          logger.info(
            { profile: result.profileName, host: result.host },
            "Using configuration profile"
          );
        } else {
          logger.info({ preset: result.presetName }, "Using configuration preset");
        }
      }
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      logger.error({ error: message }, "Failed to load profile");
      process.exit(1);
    }
  }
 
  // Step 3: Load project config (adds restrictions on top of profile)
  if (!cliArgs.noProjectConfig) {
    try {
      const projectConfig = await findProjectConfig(process.cwd());
      if (projectConfig) {
        const summary = getProjectConfigSummary(projectConfig);
        logger.info(
          {
            path: projectConfig.configPath,
            preset: summary.presetSummary,
            profile: summary.profileSummary,
          },
          "Loaded project configuration (restrictions applied)"
        );
 
        // Note: Project config is loaded and logged but not yet enforced.
        // Scope restrictions require integration with tool execution layer.
        // See: https://github.com/structured-world/gitlab-mcp/issues/61
      }
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      logger.warn({ error: message }, "Failed to load project config, continuing without it");
    }
  }
 
  // Step 4: Set default project/namespace from auto-discovery if available
  if (autoDiscoveryResult) {
    // Set default project path if not already set
    process.env.GITLAB_DEFAULT_PROJECT ??= autoDiscoveryResult.projectPath;
 
    // Extract namespace using shared utility
    const namespace = extractNamespaceFromPath(autoDiscoveryResult.projectPath);
    Eif (namespace) {
      process.env.GITLAB_DEFAULT_NAMESPACE ??= namespace;
    }
 
    logger.debug(
      {
        defaultProject: process.env.GITLAB_DEFAULT_PROJECT,
        defaultNamespace: process.env.GITLAB_DEFAULT_NAMESPACE,
      },
      "Default context set from auto-discovery"
    );
  }
 
  // Start the server
  await startServer();
}
 
main().catch((error: unknown) => {
  logger.error(`Failed to start GitLab MCP Server: ${String(error)}`);
  process.exit(1);
});