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

100% Statements 82/82
91.8% Branches 56/61
100% Functions 3/3
100% Lines 82/82

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          2x 2x   2x 2x 2x 2x 2x           2x   20x 20x 20x   20x 1x 1x       1x     19x 1x 1x       1x       18x                                         18x 1x       17x         4x 4x 3x   1x       17x 1x       16x         16x 1x             15x   6x 6x 2x 2x       13x 5x 5x   5x 3x       3x 2x   1x       3x 1x   2x     4x 4x 1x   3x       11x   11x 1x       10x 10x 8x 2x 1x 1x 1x     10x                     10x 10x   10x 10x 9x     9x         9x 2x 2x 2x 1x 1x   1x 1x       9x                   1x 1x 1x 1x      
/**
 * Server (HTTP/SSE) setup flow.
 * Handles Docker-based deployment configuration.
 */
 
import * as p from '@clack/prompts';
import { randomBytes } from 'crypto';
import { DiscoveryResult, SetupResult, DockerDeploymentType } from '../types';
import { initDockerConfig, startContainer } from '../../docker/docker-utils';
import { completionDependencyError, getContainerRuntime } from '../../docker/container-runtime';
import { DEFAULT_DOCKER_CONFIG } from '../../docker/types';
import { promptOAuthIssuer } from '../../docker/oauth-issuer-prompt';
import { runToolSelectionFlow, applyManualCategories } from './tool-selection';
 
/**
 * Run the server (HTTP/SSE) setup flow.
 * Guides user through Docker deployment configuration.
 */
export async function runServerSetupFlow(discovery: DiscoveryResult): Promise<SetupResult> {
  // Check container runtime prerequisites
  const status = discovery.docker;
  const runtime = getContainerRuntime();
  const runtimeLabel = runtime.runtime === 'podman' ? 'Podman' : 'Docker';
 
  if (!status.dockerInstalled) {
    p.log.error('No container runtime (Docker or Podman) is installed.');
    p.note(
      'Install Docker: https://docs.docker.com/get-docker/\nOr Podman: https://podman.io/getting-started/installation',
      'Install Runtime',
    );
    return { success: false, mode: 'server', error: 'Container runtime not installed' };
  }
 
  if (!status.composeInstalled) {
    p.log.error(`No compose tool found for ${runtimeLabel}.`);
    p.note(
      `A compose tool is required.\nFor Docker: bundled with Docker Desktop or 'docker compose'\nFor Podman: install podman-compose`,
      'Install Compose',
    );
    return { success: false, mode: 'server', error: 'Compose tool not installed' };
  }
 
  // Step 1: Deployment type
  const deploymentType = await p.select<DockerDeploymentType>({
    message: 'Deployment type:',
    options: [
      {
        value: 'standalone' as DockerDeploymentType,
        label: 'Docker standalone',
        hint: 'Stateless, for dev/testing',
      },
      {
        value: 'external-db' as DockerDeploymentType,
        label: 'Docker + external PostgreSQL',
        hint: 'Production with existing database',
      },
      {
        value: 'compose-bundle' as DockerDeploymentType,
        label: 'Docker Compose bundle',
        hint: 'All-in-one with postgres included',
      },
    ],
  });
 
  if (p.isCancel(deploymentType)) {
    return { success: false, mode: 'server', error: 'Cancelled' };
  }
 
  // Step 2: Port configuration
  const port = await p.text({
    message: 'SSE port for MCP server:',
    placeholder: '3333',
    initialValue: '3333',
    validate: (value) => {
      const num = parseInt(value ?? '', 10);
      if (isNaN(num) || num < 1 || num > 65535) {
        return 'Port must be between 1 and 65535';
      }
      return undefined;
    },
  });
 
  if (p.isCancel(port)) {
    return { success: false, mode: 'server', error: 'Cancelled' };
  }
 
  // Step 3: OAuth configuration
  const enableOAuth = await p.confirm({
    message: 'Enable OAuth for multi-user support?',
    initialValue: deploymentType !== 'standalone',
  });
 
  if (p.isCancel(enableOAuth)) {
    return { success: false, mode: 'server', error: 'Cancelled' };
  }
 
  let oauthSessionSecret: string | undefined;
  let databaseUrl: string | undefined;
  let oauthIssuer: string | undefined;
 
  if (enableOAuth && deploymentType !== 'standalone') {
    // PostgreSQL deployments start the server only after a one-shot migration.
    const unsupported = completionDependencyError(runtime);
    if (unsupported) {
      p.log.error(unsupported);
      return { success: false, mode: 'server', error: unsupported };
    }
  }
 
  if (enableOAuth) {
    oauthSessionSecret = randomBytes(32).toString('hex');
    p.log.info('Session secret generated and stored in .env file (not in compose).');
 
    if (deploymentType === 'external-db') {
      const dbUrl = await p.text({
        message: 'PostgreSQL DATABASE_URL:',
        placeholder: 'postgresql://user:pass@host:5432/gitlab_mcp',
        validate: (v) => {
          if (!v?.startsWith('postgresql://')) {
            return 'Must be a valid PostgreSQL URL';
          }
          return undefined;
        },
      });
 
      if (p.isCancel(dbUrl)) {
        return { success: false, mode: 'server', error: 'Cancelled' };
      }
      databaseUrl = dbUrl;
    }
 
    const issuer = await promptOAuthIssuer(Number.parseInt(port, 10));
    if (p.isCancel(issuer)) {
      return { success: false, mode: 'server', error: 'Cancelled' };
    }
    oauthIssuer = issuer;
  }
 
  // Step 4: Tool configuration
  const toolConfig = await runToolSelectionFlow();
 
  if (!toolConfig) {
    return { success: false, mode: 'server', error: 'Cancelled' };
  }
 
  // Step 5: Create Docker configuration with tool selection and deployment type applied
  const toolEnv: Record<string, string> = {};
  if (toolConfig.mode === 'preset' && toolConfig.preset) {
    toolEnv.GITLAB_PROFILE = toolConfig.preset;
  } else if (toolConfig.mode === 'advanced' && toolConfig.envOverrides) {
    Object.assign(toolEnv, toolConfig.envOverrides);
  } else Eif (toolConfig.mode === 'manual' && toolConfig.enabledCategories) {
    applyManualCategories(toolConfig.enabledCategories, toolEnv);
  }
 
  const config = {
    ...DEFAULT_DOCKER_CONFIG,
    port: parseInt(port, 10),
    deploymentType,
    oauthEnabled: enableOAuth,
    oauthSessionSecret,
    oauthIssuer,
    databaseUrl,
    environment: Object.keys(toolEnv).length > 0 ? toolEnv : undefined,
  };
 
  const spinner = p.spinner();
  spinner.start('Creating Docker configuration...');
 
  try {
    initDockerConfig(config);
    spinner.stop('Docker configuration created!');
 
    // Step 6: Start container
    const startNow = await p.confirm({
      message: 'Start the container now?',
      initialValue: true,
    });
 
    if (!p.isCancel(startNow) && startNow) {
      spinner.start('Starting container...');
      const result = startContainer();
      if (result.success) {
        spinner.stop('Container started!');
        p.log.success(`MCP server running at http://localhost:${port}`);
      } else {
        spinner.stop('Failed to start container');
        p.log.error(result.error ?? 'Unknown error');
      }
    }
 
    return {
      success: true,
      mode: 'server',
      dockerConfig: {
        port: parseInt(port, 10),
        deploymentType,
        instances: [],
      },
    };
  } catch (error) {
    spinner.stop('Configuration failed');
    const msg = error instanceof Error ? error.message : String(error);
    p.log.error(msg);
    return { success: false, mode: 'server', error: msg };
  }
}