All files / src/cli/setup/flows local-setup.ts

90.81% Statements 89/98
67.18% Branches 43/64
77.77% Functions 7/9
90.52% Lines 86/95

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 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240          2x   2x 2x 2x   2x 2x           2x   15x               15x 1x       14x 12x   2x                 2x 1x   1x       13x         13x 1x     12x 1x 1x               1x         1x 1x 1x     1x 1x           12x                   12x 1x     11x     11x 11x   11x   11x 1x 1x 1x     10x 10x           10x   10x 1x       9x     9x   9x   5x 5x   5x 5x 5x 5x       4x 4x 4x   4x 4x   4x 3x 3x 3x 3x 3x 3x       4x 1x 1x 1x 1x       4x     3x                       9x           9x 9x     9x       9x       9x                     9x   9x 4x 4x     5x   5x               5x       5x    
/**
 * Local (stdio) setup flow.
 * Handles GitLab authentication, tool configuration, and client installation.
 */
 
import * as p from "@clack/prompts";
import { DiscoveryResult, SetupResult, ToolConfig } from "../types";
import { InstallableClient, CLIENT_METADATA } from "../../install/types";
import { testConnection, validateGitLabUrl, getPatCreationUrl } from "../../init/connection";
import { openUrl } from "../../init/browser";
import { McpServerConfig } from "../../init/types";
import { installToClients } from "../../install/installers";
import { runToolSelectionFlow, applyManualCategories } from "./tool-selection";
 
/**
 * Run the local (stdio) setup flow.
 * Guides user through GitLab connection, tool selection, and client installation.
 */
export async function runLocalSetupFlow(discovery: DiscoveryResult): Promise<SetupResult> {
  // Step 1: GitLab instance selection
  const instanceType = await p.select({
    message: "Which GitLab instance?",
    options: [
      { value: "saas" as const, label: "GitLab.com (SaaS)" },
      { value: "self-hosted" as const, label: "Self-hosted GitLab" },
    ],
  });
 
  if (p.isCancel(instanceType)) {
    return { success: false, mode: "local", error: "Cancelled" };
  }
 
  let instanceUrl: string;
  if (instanceType === "saas") {
    instanceUrl = "https://gitlab.com";
  } else {
    const urlInput = await p.text({
      message: "Enter your GitLab instance URL:",
      placeholder: "https://gitlab.example.com",
      validate: value => {
        const result = validateGitLabUrl(value ?? "");
        return result.valid ? undefined : result.error;
      },
    });
 
    if (p.isCancel(urlInput)) {
      return { success: false, mode: "local", error: "Cancelled" };
    }
    instanceUrl = urlInput.replace(/\/+$/, "").replace(/\/api\/v4$/i, "");
  }
 
  // Step 2: Authentication
  const hasToken = await p.confirm({
    message: "Do you already have a GitLab Personal Access Token (PAT)?",
    initialValue: false,
  });
 
  if (p.isCancel(hasToken)) {
    return { success: false, mode: "local", error: "Cancelled" };
  }
 
  if (!hasToken) {
    const patUrl = getPatCreationUrl(instanceUrl);
    p.note(
      `You need a Personal Access Token with these scopes:\n` +
        `  - api (full API access)\n` +
        `  - read_user (read user info)\n\n` +
        `Token URL: ${patUrl}`,
      "Create a Personal Access Token"
    );
 
    const openBrowser = await p.confirm({
      message: "Open browser to create token?",
      initialValue: true,
    });
 
    Eif (!p.isCancel(openBrowser) && openBrowser) {
      const opened = await openUrl(patUrl);
      Iif (opened) {
        p.log.info("Browser opened. Create your token and copy it.");
      } else {
        p.log.warn("Could not open browser automatically");
        p.note(patUrl, "Open this URL manually:");
      }
    }
  }
 
  // Step 3: Enter token
  const tokenInput = await p.password({
    message: "Enter your Personal Access Token:",
    validate: value => {
      if (!value || value.length < 10) {
        return "Token is too short";
      }
      return undefined;
    },
  });
 
  if (p.isCancel(tokenInput)) {
    return { success: false, mode: "local", error: "Cancelled" };
  }
 
  const token = tokenInput;
 
  // Step 4: Test connection
  const spinner = p.spinner();
  spinner.start("Testing connection...");
 
  const connectionResult = await testConnection(instanceUrl, token);
 
  if (!connectionResult.success) {
    spinner.stop("Connection failed");
    p.log.error(`Connection error: ${connectionResult.error ?? "Unknown error"}`);
    return { success: false, mode: "local", error: connectionResult.error };
  }
 
  spinner.stop("Connection successful!");
  p.log.success(
    `Connected as ${connectionResult.username ?? "unknown user"}` +
      (connectionResult.gitlabVersion ? ` (GitLab ${connectionResult.gitlabVersion})` : "")
  );
 
  // Step 5: Tool configuration
  const toolConfig = await runToolSelectionFlow();
 
  if (!toolConfig) {
    return { success: false, mode: "local", error: "Cancelled" };
  }
 
  // Step 6: Build server configuration
  const serverConfig = buildServerConfig(instanceUrl, token, toolConfig);
 
  // Step 7: Select clients to install
  const targetClients = await selectClients(discovery);
 
  if (!targetClients || targetClients.length === 0) {
    // No clients selected - just show the config
    p.log.step("Generated configuration:");
    const configJson = JSON.stringify({ mcpServers: { gitlab: serverConfig } }, null, 2);
    // Mask token in display
    const masked = configJson.replace(/("GITLAB_TOKEN"\s*:\s*")((?:\\.|[^"\\])*)(")/g, "$1****$3");
    p.note(masked, "MCP Server Configuration");
    p.log.warn("Replace **** with your actual token in the config file.");
    return { success: true, mode: "local" };
  }
 
  // Step 8: Install to clients
  spinner.start("Installing configuration...");
  const results = installToClients(targetClients, serverConfig, true);
  spinner.stop("Installation complete!");
 
  const successful = results.filter(r => r.success);
  const failed = results.filter(r => !r.success);
 
  if (successful.length > 0) {
    p.log.success(`Installed to ${successful.length} client(s):`);
    for (const result of successful) {
      const metadata = CLIENT_METADATA[result.client];
      let info = `  ✓ ${metadata.name}`;
      Eif (result.configPath) info += ` (${result.configPath})`;
      console.log(info);
    }
  }
 
  if (failed.length > 0) {
    p.log.error(`Failed for ${failed.length} client(s):`);
    for (const result of failed) {
      const metadata = CLIENT_METADATA[result.client];
      console.log(`  ✗ ${metadata.name}: ${result.error}`);
    }
  }
 
  return {
    success: successful.length > 0,
    mode: "local",
    configuredClients: successful.map(r => r.client),
  };
}
 
/**
 * Build McpServerConfig from wizard inputs
 */
function buildServerConfig(
  instanceUrl: string,
  token: string,
  toolConfig: ToolConfig
): McpServerConfig {
  const env: Record<string, string> = {
    GITLAB_API_URL: instanceUrl,
    GITLAB_TOKEN: token,
  };
 
  // Apply tool configuration
  Eif (toolConfig.mode === "preset" && toolConfig.preset) {
    env.GITLAB_PROFILE = toolConfig.preset;
  }
 
  Iif (toolConfig.mode === "manual" && toolConfig.enabledCategories) {
    applyManualCategories(toolConfig.enabledCategories, env);
  }
 
  Iif (toolConfig.mode === "advanced" && toolConfig.envOverrides) {
    Object.assign(env, toolConfig.envOverrides);
  }
 
  return {
    command: "npx",
    args: ["-y", "@structured-world/gitlab-mcp@latest"],
    env,
  };
}
 
/**
 * Select clients for installation from detected clients
 */
async function selectClients(discovery: DiscoveryResult): Promise<InstallableClient[] | null> {
  const detected = discovery.clients.detected;
 
  if (detected.length === 0) {
    p.log.warn("No MCP clients detected. Configuration will be displayed instead.");
    return null;
  }
 
  const selectedClients = await p.multiselect({
    message: "Select clients to install to:",
    options: detected.map(result => ({
      value: result.client,
      label: CLIENT_METADATA[result.client].name,
      hint: result.alreadyConfigured ? "already configured (will overwrite)" : undefined,
    })),
    required: false,
  });
 
  Iif (p.isCancel(selectedClients)) {
    return null;
  }
 
  return selectedClients;
}