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 | 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 8x 8x 6x 6x 18x 18x 18x 18x 18x 18x 18x 18x 4x 4x 4x 4x 4x 4x 18x 8x 8x 8x 5x 3x 3x 3x 1x 1x 18x 3x 3x 3x 3x 3x 3x 1x 1x 18x 19x 19x 19x 19x 19x 19x 19x 19x 18x 6x 1x 1x 6x 1x 1x | 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 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,
authorizeHandler,
pollHandler,
tokenHandler,
healthHandler,
} from "./oauth/index";
// Note: oauthAuthMiddleware is available for future use on protected endpoints
// import { oauthAuthMiddleware } from "./middleware/index";
// Create server instance
export const server = new Server(
{
name: packageName,
version: packageVersion,
},
{
capabilities: {
tools: {},
},
}
);
// 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
* - /authorize - Authorization endpoint (initiates device flow)
* - /oauth/poll - Device flow polling endpoint
* - /token - Token exchange endpoint
* - /health - Health check endpoint
*
* @param app - Express application
*/
function registerOAuthEndpoints(app: Express): void {
// OAuth discovery metadata (no auth required)
app.get("/.well-known/oauth-authorization-server", metadataHandler);
// Authorization endpoint - initiates device flow (no auth required)
app.get("/authorize", authorizeHandler);
// Device flow polling endpoint (no auth required)
app.get("/oauth/poll", pollHandler);
// 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);
// 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);
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()}`);
// 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);
// 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) => {
logger.debug("Messages endpoint hit!");
const sessionId = req.query.sessionId as string;
if (!sessionId || !sseTransports[sessionId]) {
return res.status(404).json({ error: "Session not found" });
}
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);
// Register OAuth endpoints if OAuth mode is enabled
if (isOAuthEnabled()) {
registerOAuthEndpoints(app);
}
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;
try {
let transport: StreamableHTTPServerTransport;
if (sessionId && sessionId in streamableTransports) {
// Use existing transport for this session
transport = streamableTransports[sessionId];
await transport.handleRequest(req, res, req.body);
} 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})`);
},
onsessionclosed: (closedSessionId: string) => {
delete streamableTransports[closedSessionId];
logger.info(`MCP session closed: ${closedSessionId}`);
},
});
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
}
} 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);
// Register OAuth endpoints if OAuth mode is enabled
Iif (isOAuthEnabled()) {
registerOAuthEndpoints(app);
}
// 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) => {
logger.debug("SSE messages endpoint hit!");
const sessionId = req.query.sessionId as string;
if (!sessionId || !sseTransports[sessionId]) {
return res.status(404).json({ error: "Session not found" });
}
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)
app.all("/mcp", async (req, res) => {
const sessionId = req.headers["mcp-session-id"] as string;
try {
let transport: StreamableHTTPServerTransport;
Iif (sessionId && sessionId in streamableTransports) {
transport = streamableTransports[sessionId];
await transport.handleRequest(req, res, req.body);
} 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})`);
},
onsessionclosed: (closedSessionId: string) => {
delete streamableTransports[closedSessionId];
logger.info(`MCP session closed: ${closedSessionId}`);
},
});
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
}
} 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
process.on("SIGINT", () => {
logger.info("Shutting down GitLab MCP Server...");
process.exit(0);
});
process.on("SIGTERM", () => {
logger.info("Shutting down GitLab MCP Server...");
process.exit(0);
});
|