All files / src server.ts

43.29% Statements 113/261
27.35% Branches 29/106
42.85% Functions 15/35
43.29% Lines 113/261

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 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 6416x 6x 6x 6x 6x   6x 6x 6x                   6x 6x 6x     6x                                 6x     6x     6x                                 6x                                                                                                                           38x             18x 18x                                                           18x 18x                                         18x   18x       18x               19x       26x   26x     26x 2x 2x       24x 18x     18x       6x 6x     6x   26x 26x         26x 26x     26x     26x         26x   26x   26x   8x 8x 6x 6x                                                                                                                                                                                                                                                                                                                                                                                 18x 18x 18x     18x     18x     18x             18x                                 18x         18x 18x     18x 4x 4x 4x   4x 4x 4x     18x 8x 8x   8x 5x 5x     3x 3x 3x   1x 1x           18x 3x     3x 3x 3x 3x   3x                       3x     3x                             3x       3x     3x       3x                                 3x 3x     1x 1x       18x 19x 19x 19x     19x 19x 19x 19x           19x   18x             12x   12x   12x     12x     12x     6x 6x           6x 6x          
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import express, { Express } from "express";
import * as http from "http";
import * as https from "https";
import * as fs from "fs";
import {
  HOST,
  PORT,
  SSL_CERT_PATH,
  SSL_KEY_PATH,
  SSL_CA_PATH,
  SSL_PASSPHRASE,
  TRUST_PROXY,
} from "./config";
import { TransportMode } from "./types";
import { packageName, packageVersion } from "./config";
import { setupHandlers } from "./handlers";
import { logger } from "./logger";
 
// OAuth imports
import {
  loadOAuthConfig,
  validateStaticConfig,
  isOAuthEnabled,
  getAuthModeDescription,
  metadataHandler,
  protectedResourceHandler,
  authorizeHandler,
  pollHandler,
  callbackHandler,
  tokenHandler,
  healthHandler,
  registerHandler,
  sessionStore,
  runWithTokenContext,
} from "./oauth/index";
// Middleware imports
import { oauthAuthMiddleware, rateLimiterMiddleware } from "./middleware/index";
 
// Schema mode auto-detection
import { setDetectedSchemaMode } from "./utils/schema-utils";
 
// Create server instance
export const server = new Server(
  {
    name: packageName,
    version: packageVersion,
  },
  {
    capabilities: {
      tools: {},
    },
  }
);
 
// Auto-detect schema mode from clientInfo after initialization
// Used when GITLAB_SCHEMA_MODE=auto to determine flat vs discriminated
// NOTE: This works correctly for stdio mode (single client). For HTTP/SSE with multiple
// concurrent sessions, auto-detection will use the most recent client's preference for
// all sessions. Use explicit GITLAB_SCHEMA_MODE=flat|discriminated for multi-session deployments.
server.oninitialized = () => {
  const clientVersion = server.getClientVersion();
  setDetectedSchemaMode(clientVersion?.name);
};
 
// Terminal colors for logging (currently unused)
// const colorGreen = '\x1b[32m';
// const colorReset = '\x1b[0m';
 
/**
 * Register OAuth endpoints on an Express app
 *
 * Adds:
 * - /.well-known/oauth-authorization-server - OAuth metadata
 * - /.well-known/oauth-protected-resource - Protected resource metadata (RFC 9470)
 * - /authorize - Authorization endpoint (supports both Device Flow and Authorization Code Flow)
 * - /oauth/poll - Device flow polling endpoint
 * - /oauth/callback - Authorization Code Flow callback from GitLab
 * - /token - Token exchange endpoint
 * - /health - Health check endpoint
 *
 * @param app - Express application
 */
function registerOAuthEndpoints(app: Express): void {
  // NOTE: Rate limiting is applied via rateLimiterMiddleware() BEFORE this function is called.
  // All routes registered here are protected by the global rate limiter middleware.
 
  // OAuth discovery metadata (no auth required)
  app.get("/.well-known/oauth-authorization-server", metadataHandler);
 
  // Protected Resource Metadata (RFC 9470) - required by Claude.ai custom connectors
  app.get("/.well-known/oauth-protected-resource", protectedResourceHandler);
 
  // Authorization endpoint - supports both flows:
  // - Device Flow (no redirect_uri) - returns HTML page
  // - Authorization Code Flow (with redirect_uri) - redirects to GitLab
  app.get("/authorize", authorizeHandler);
 
  // Device flow polling endpoint (no auth required)
  app.get("/oauth/poll", pollHandler);
 
  // Authorization Code Flow callback from GitLab
  // GitLab redirects here after user authorizes, then we redirect to client
  app.get("/oauth/callback", callbackHandler);
 
  // Token endpoint - exchange code for tokens (no auth required)
  // Uses URL-encoded body as per OAuth spec
  app.post("/token", express.urlencoded({ extended: true }), tokenHandler);
 
  // Dynamic Client Registration endpoint (RFC 7591) - required by Claude.ai
  app.post("/register", express.json(), registerHandler);
 
  // Health check endpoint
  app.get("/health", healthHandler);
 
  logger.info("OAuth endpoints registered");
}
 
/**
 * Check if TLS/HTTPS is enabled via SSL certificate configuration
 */
function isTLSEnabled(): boolean {
  return !!(SSL_CERT_PATH && SSL_KEY_PATH);
}
 
/**
 * Load TLS options from certificate files
 */
function loadTLSOptions(): https.ServerOptions | undefined {
  Eif (!SSL_CERT_PATH || !SSL_KEY_PATH) {
    return undefined;
  }
 
  try {
    const options: https.ServerOptions = {
      cert: fs.readFileSync(SSL_CERT_PATH),
      key: fs.readFileSync(SSL_KEY_PATH),
    };
 
    if (SSL_CA_PATH) {
      options.ca = fs.readFileSync(SSL_CA_PATH);
      logger.info(`CA certificate loaded from ${SSL_CA_PATH}`);
    }
 
    if (SSL_PASSPHRASE) {
      options.passphrase = SSL_PASSPHRASE;
    }
 
    logger.info(`TLS certificates loaded from ${SSL_CERT_PATH}`);
    return options;
  } catch (error: unknown) {
    logger.error({ err: error }, "Failed to load TLS certificates");
    throw new Error(`Failed to load TLS certificates: ${String(error)}`);
  }
}
 
/**
 * Configure Express trust proxy setting for reverse proxy deployments
 */
function configureTrustProxy(app: Express): void {
  Eif (!TRUST_PROXY) {
    return;
  }
 
  // Parse trust proxy value
  let trustValue: boolean | string | number = TRUST_PROXY;
  if (TRUST_PROXY === "true" || TRUST_PROXY === "1") {
    trustValue = true;
  } else if (TRUST_PROXY === "false" || TRUST_PROXY === "0") {
    trustValue = false;
  } else if (!isNaN(Number(TRUST_PROXY))) {
    trustValue = Number(TRUST_PROXY);
  }
 
  app.set("trust proxy", trustValue);
  logger.info(`Trust proxy configured: ${String(trustValue)}`);
}
 
/**
 * Start an HTTP or HTTPS server based on TLS configuration
 */
function startHttpServer(app: Express, callback: () => void): void {
  const tlsOptions = loadTLSOptions();
 
  Iif (tlsOptions) {
    const httpsServer = https.createServer(tlsOptions, app as http.RequestListener);
    httpsServer.listen(Number(PORT), HOST, callback);
  } else {
    app.listen(Number(PORT), HOST, callback);
  }
}
 
/**
 * Get the protocol prefix for URLs
 */
function getProtocol(): string {
  return isTLSEnabled() ? "https" : "http";
}
 
function determineTransportMode(): TransportMode {
  const args = process.argv.slice(2);
 
  logger.info(`Transport mode detection: args=${JSON.stringify(args)}, PORT=${PORT}`);
 
  // Check for explicit stdio mode first
  if (args.includes("stdio")) {
    logger.info("Selected stdio mode (explicit argument)");
    return "stdio" as TransportMode;
  }
 
  // If PORT environment variable is present, start in dual transport mode (SSE + StreamableHTTP)
  if (process.env.PORT) {
    logger.info(
      "Selected dual transport mode (SSE + StreamableHTTP) - PORT environment variable detected"
    );
    return "dual" as TransportMode;
  }
 
  // Default to stdio mode when no PORT is specified
  logger.info("Selected stdio mode (no PORT environment variable)");
  return "stdio" as TransportMode;
}
 
export async function startServer(): Promise<void> {
  // Validate configuration based on auth mode
  const oauthConfig = loadOAuthConfig();
  Iif (oauthConfig) {
    logger.info("Starting in OAuth mode (per-user authentication)");
    logger.info(`OAuth client ID: ${oauthConfig.gitlabClientId}`);
  } else {
    // Validate static token configuration
    validateStaticConfig();
    logger.info("Starting in static token mode (shared GITLAB_TOKEN)");
  }
 
  logger.info(`Authentication mode: ${getAuthModeDescription()}`);
 
  // Initialize session store (required for file-based and PostgreSQL persistence)
  Iif (oauthConfig) {
    await sessionStore.initialize();
  }
 
  // Setup request handlers
  await setupHandlers(server);
 
  const transportMode = determineTransportMode();
 
  switch (transportMode) {
    case "stdio": {
      const transport = new StdioServerTransport();
      await server.connect(transport);
      logger.info("GitLab MCP Server running on stdio");
      break;
    }
 
    case "sse": {
      logger.info("Setting up SSE mode with MCP SDK...");
      const app = express();
      app.use(express.json());
 
      // Configure trust proxy for reverse proxy deployments
      configureTrustProxy(app);
 
      // Rate limiting middleware (protects anonymous requests, authenticated users skip)
      app.use(rateLimiterMiddleware());
 
      // Register OAuth endpoints if OAuth mode is enabled
      if (isOAuthEnabled()) {
        registerOAuthEndpoints(app);
      }
 
      const sseTransports: { [sessionId: string]: SSEServerTransport } = {};
 
      // SSE endpoint for establishing the stream
      app.get("/sse", async (req, res) => {
        logger.debug("SSE endpoint hit!");
        const transport = new SSEServerTransport("/messages", res);
 
        // Connect the server to this transport (this calls start() automatically)
        await server.connect(transport);
 
        // Store transport by session ID for message routing
        const sessionId = transport.sessionId;
        sseTransports[sessionId] = transport;
        logger.debug(`SSE transport created with session: ${sessionId}`);
      });
 
      // Messages endpoint for receiving JSON-RPC messages
      app.post("/messages", async (req, res): Promise<void> => {
        logger.debug("Messages endpoint hit!");
        const sessionId = req.query.sessionId as string;
 
        if (!sessionId || !sseTransports[sessionId]) {
          res.status(404).json({ error: "Session not found" });
          return;
        }
 
        try {
          const transport = sseTransports[sessionId];
          await transport.handlePostMessage(req, res, req.body);
        } catch (error: unknown) {
          logger.error({ err: error }, "Error handling SSE message");
          res.status(500).json({ error: "Internal server error" });
        }
      });
 
      startHttpServer(app, () => {
        const url = `${getProtocol()}://${HOST}:${PORT}`;
        logger.info(`GitLab MCP Server SSE running on ${url}`);
        if (isTLSEnabled()) {
          logger.info("TLS/HTTPS enabled");
        }
        logger.info("SSE server started successfully");
      });
      break;
    }
 
    case "streamable-http": {
      const app = express();
      app.use(express.json());
 
      // Configure trust proxy for reverse proxy deployments
      configureTrustProxy(app);
 
      // Rate limiting middleware (protects anonymous requests, authenticated users skip)
      app.use(rateLimiterMiddleware());
 
      // Register OAuth endpoints if OAuth mode is enabled
      if (isOAuthEnabled()) {
        registerOAuthEndpoints(app);
      }
 
      // Middleware to ensure Accept header includes text/event-stream for MCP endpoints
      // This fixes compatibility with clients that don't send the full Accept header
      // as required by MCP spec (e.g., when headers are modified by reverse proxies)
      app.use("/mcp", (req, res, next) => {
        const accept = req.headers.accept ?? "";
        if (req.method === "POST" && !accept.includes("text/event-stream")) {
          req.headers.accept = accept
            ? `${accept}, text/event-stream`
            : "application/json, text/event-stream";
          logger.debug(
            { originalAccept: accept, newAccept: req.headers.accept },
            "Modified Accept header for MCP compatibility"
          );
        }
        next();
      });
 
      // OAuth authentication middleware for MCP endpoints (when OAuth mode is enabled)
      if (isOAuthEnabled()) {
        app.use("/mcp", oauthAuthMiddleware);
      }
 
      const streamableTransports: { [sessionId: string]: StreamableHTTPServerTransport } = {};
 
      // Single endpoint that handles both GET (SSE) and POST (JSON-RPC) requests
      // This follows MCP SDK pattern where StreamableHTTP transport handles both internally
      app.all("/mcp", async (req, res) => {
        const sessionId = req.headers["mcp-session-id"] as string;
 
        // Get OAuth token info from middleware (stored in res.locals)
        const oauthSessionId = res.locals.oauthSessionId as string | undefined;
        const gitlabToken = res.locals.gitlabToken as string | undefined;
        const gitlabUserId = res.locals.gitlabUserId as number | undefined;
        const gitlabUsername = res.locals.gitlabUsername as string | undefined;
 
        // Helper to handle request with proper token context
        const handleWithContext = async (
          transport: StreamableHTTPServerTransport
        ): Promise<void> => {
          if (gitlabToken && oauthSessionId && gitlabUserId && gitlabUsername) {
            // Wrap transport.handleRequest in token context so MCP handlers have access
            await runWithTokenContext(
              {
                gitlabToken,
                gitlabUserId,
                gitlabUsername,
                sessionId: oauthSessionId,
              },
              async () => {
                await transport.handleRequest(req, res, req.body);
              }
            );
          } else {
            // No OAuth token - direct handling (static token mode or unauthenticated)
            await transport.handleRequest(req, res, req.body);
          }
        };
 
        try {
          let transport: StreamableHTTPServerTransport;
 
          if (sessionId && sessionId in streamableTransports) {
            // Use existing transport for this session
            transport = streamableTransports[sessionId];
            await handleWithContext(transport);
          } else {
            // Create new transport (handles both SSE and JSON-RPC internally)
            transport = new StreamableHTTPServerTransport({
              sessionIdGenerator: () => Math.random().toString(36).substring(7),
              onsessioninitialized: (newSessionId: string) => {
                streamableTransports[newSessionId] = transport;
                logger.info(`MCP session initialized: ${newSessionId} (method: ${req.method})`);
 
                // Associate MCP session with OAuth session if authenticated
                if (oauthSessionId) {
                  sessionStore.associateMcpSession(newSessionId, oauthSessionId);
                }
              },
              onsessionclosed: (closedSessionId: string) => {
                delete streamableTransports[closedSessionId];
                sessionStore.removeMcpSessionAssociation(closedSessionId);
                logger.info(`MCP session closed: ${closedSessionId}`);
              },
            });
            await server.connect(transport);
            await handleWithContext(transport);
          }
        } catch (error: unknown) {
          logger.error({ err: error }, "Error in StreamableHTTP transport");
          res.status(500).json({ error: "Internal server error" });
        }
      });
 
      startHttpServer(app, () => {
        const url = `${getProtocol()}://${HOST}:${PORT}`;
        logger.info(`GitLab MCP Server running on ${url}/mcp`);
        if (isTLSEnabled()) {
          logger.info("TLS/HTTPS enabled");
        }
        logger.info("Supports both SSE (GET) and JSON-RPC (POST) on same endpoint");
      });
      break;
    }
 
    case "dual": {
      logger.info("Setting up dual transport mode (SSE + StreamableHTTP)...");
      const app = express();
      app.use(express.json());
 
      // Configure trust proxy for reverse proxy deployments
      configureTrustProxy(app);
 
      // Rate limiting middleware (protects anonymous requests, authenticated users skip)
      app.use(rateLimiterMiddleware());
 
      // Register OAuth endpoints if OAuth mode is enabled
      Iif (isOAuthEnabled()) {
        registerOAuthEndpoints(app);
      }
 
      // Middleware to ensure Accept header includes text/event-stream for MCP endpoints
      // This fixes compatibility with clients that don't send the full Accept header
      // as required by MCP spec (e.g., when headers are modified by reverse proxies)
      app.use(["/", "/mcp"], (req, res, next) => {
        const accept = req.headers.accept ?? "";
        if (req.method === "POST" && !accept.includes("text/event-stream")) {
          // Add text/event-stream to Accept header for POST requests
          req.headers.accept = accept
            ? `${accept}, text/event-stream`
            : "application/json, text/event-stream";
          logger.debug(
            { originalAccept: accept, newAccept: req.headers.accept },
            "Modified Accept header for MCP compatibility"
          );
        }
        next();
      });
 
      // OAuth authentication middleware for MCP endpoints (when OAuth mode is enabled)
      // Returns 401 with WWW-Authenticate header if no valid token, triggering OAuth flow
      Iif (isOAuthEnabled()) {
        app.use(["/", "/mcp"], oauthAuthMiddleware);
      }
 
      // Transport storage for both SSE and StreamableHTTP
      const sseTransports: { [sessionId: string]: SSEServerTransport } = {};
      const streamableTransports: { [sessionId: string]: StreamableHTTPServerTransport } = {};
 
      // SSE Transport Endpoints (backwards compatibility)
      app.get("/sse", async (req, res) => {
        logger.debug("SSE endpoint hit!");
        const transport = new SSEServerTransport("/messages", res);
        await server.connect(transport);
 
        const sessionId = transport.sessionId;
        sseTransports[sessionId] = transport;
        logger.debug(`SSE transport created with session: ${sessionId}`);
      });
 
      app.post("/messages", async (req, res): Promise<void> => {
        logger.debug("SSE messages endpoint hit!");
        const sessionId = req.query.sessionId as string;
 
        if (!sessionId || !sseTransports[sessionId]) {
          res.status(404).json({ error: "Session not found" });
          return;
        }
 
        try {
          const transport = sseTransports[sessionId];
          await transport.handlePostMessage(req, res, req.body);
        } catch (error: unknown) {
          logger.error({ err: error }, "Error handling SSE message");
          res.status(500).json({ error: "Internal server error" });
        }
      });
 
      // StreamableHTTP Transport Endpoint (modern, supports both GET SSE and POST JSON-RPC)
      // Also mounted at "/" for Claude.ai custom connector compatibility
      app.all(["/", "/mcp"], async (req, res) => {
        const sessionId = req.headers["mcp-session-id"] as string;
 
        // Get OAuth token info from middleware (stored in res.locals)
        const oauthSessionId = res.locals.oauthSessionId as string | undefined;
        const gitlabToken = res.locals.gitlabToken as string | undefined;
        const gitlabUserId = res.locals.gitlabUserId as number | undefined;
        const gitlabUsername = res.locals.gitlabUsername as string | undefined;
 
        logger.info(
          {
            method: req.method,
            path: req.path,
            mcpSessionId: sessionId || "none",
            hasOAuthSession: !!oauthSessionId,
            hasToken: !!gitlabToken,
          },
          "MCP endpoint request received"
        );
 
        // Helper to handle request with proper token context
        const handleWithContext = async (
          transport: StreamableHTTPServerTransport
        ): Promise<void> => {
          Iif (gitlabToken && oauthSessionId && gitlabUserId && gitlabUsername) {
            // Wrap transport.handleRequest in token context so MCP handlers have access
            await runWithTokenContext(
              {
                gitlabToken,
                gitlabUserId,
                gitlabUsername,
                sessionId: oauthSessionId,
              },
              async () => {
                await transport.handleRequest(req, res, req.body);
              }
            );
          } else {
            // No OAuth token - direct handling (static token mode or unauthenticated)
            await transport.handleRequest(req, res, req.body);
          }
        };
 
        try {
          let transport: StreamableHTTPServerTransport;
 
          Iif (sessionId && sessionId in streamableTransports) {
            transport = streamableTransports[sessionId];
            await handleWithContext(transport);
          } else {
            transport = new StreamableHTTPServerTransport({
              sessionIdGenerator: () => Math.random().toString(36).substring(7),
              onsessioninitialized: (newSessionId: string) => {
                streamableTransports[newSessionId] = transport;
                logger.info(`MCP session initialized: ${newSessionId} (method: ${req.method})`);
 
                // Associate MCP session with OAuth session if authenticated
                if (oauthSessionId) {
                  sessionStore.associateMcpSession(newSessionId, oauthSessionId);
                }
              },
              onsessionclosed: (closedSessionId: string) => {
                delete streamableTransports[closedSessionId];
                sessionStore.removeMcpSessionAssociation(closedSessionId);
                logger.info(`MCP session closed: ${closedSessionId}`);
              },
            });
            await server.connect(transport);
            await handleWithContext(transport);
          }
        } catch (error: unknown) {
          logger.error({ err: error }, "Error in StreamableHTTP transport");
          res.status(500).json({ error: "Internal server error" });
        }
      });
 
      startHttpServer(app, () => {
        const url = `${getProtocol()}://${HOST}:${PORT}`;
        logger.info(`GitLab MCP Server running on ${url}`);
        Iif (isTLSEnabled()) {
          logger.info("TLS/HTTPS enabled");
        }
        logger.info("Dual Transport Mode Active:");
        logger.info(`  SSE endpoint: ${url}/sse (backwards compatibility)`);
        logger.info(`  StreamableHTTP endpoint: ${url}/mcp (modern, supports SSE + JSON-RPC)`);
        Iif (isOAuthEnabled()) {
          logger.info("OAuth Mode Active:");
          logger.info(`  OAuth metadata: ${url}/.well-known/oauth-authorization-server`);
          logger.info(`  Authorization: ${url}/authorize`);
          logger.info(`  Token exchange: ${url}/token`);
        }
        logger.info("Clients can use either transport as needed");
      });
      break;
    }
  }
}
 
// Graceful shutdown - save sessions to storage backend before exit
async function gracefulShutdown(signal: string): Promise<void> {
  logger.info({ signal }, "Shutting down GitLab MCP Server...");
 
  try {
    // Close session store (saves file-based sessions, disconnects PostgreSQL)
    await sessionStore.close();
    logger.info("Session store closed successfully");
  } catch (error) {
    logger.error({ err: error as Error }, "Error closing session store");
  }
 
  process.exit(0);
}
 
process.on("SIGINT", () => {
  gracefulShutdown("SIGINT").catch(err => {
    logger.error({ err }, "Error during graceful shutdown");
    process.exit(1);
  });
});
 
process.on("SIGTERM", () => {
  gracefulShutdown("SIGTERM").catch(err => {
    logger.error({ err }, "Error during graceful shutdown");
    process.exit(1);
  });
});