All files / src handlers.ts

87.23% Statements 164/188
78.94% Branches 105/133
94.44% Functions 17/18
88.52% Lines 162/183

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  8x 8x 8x 8x             8x 8x                                                       8x             26x 26x   13x 13x 13x     13x 4x 9x 6x 3x 1x   2x     13x             40x                       20x         20x 20x 1x     19x                 6x                                   22x         22x 22x 2x     20x     20x 20x 8x   20x     20x 20x 6x 6x       14x 14x   6x               8x   66x   33x   32x 32x 32x 31x   1x             1x     33x 7x     14x 7x 7x   7x             16x     16x     16x         16x 2x 2x   2x   1x   1x 1x 1x     1x 1x 1x       14x 14x 27x   8x 8x     6x   8x 19x 1x   18x       14x       7x 8x     8x 8x       8x 8x   8x 8x         8x 2x 2x 2x     8x     7x           33x 25x 25x 1x         24x         48x   24x   1x                 23x 23x   23x   23x     21x       21x 21x       2x     2x 2x 1x     1x       1x 1x         2x 1x   2x     2x         21x 21x 21x     21x 21x 21x     42x 21x 21x 21x     21x     21x 21x                   21x   42x 21x     21x 1x     20x         40x 20x                   20x   3x                 18x   18x     22x 22x     22x 22x     22x 22x                 22x 22x 22x   22x 14x 14x                       8x 8x                        
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
import { ConnectionManager } from "./services/ConnectionManager";
import { logInfo, logWarn, logError, logDebug } from "./logger";
import {
  handleGitLabError,
  GitLabStructuredError,
  isStructuredToolError,
  createTimeoutError,
  parseTimeoutError,
} from "./utils/error-handler";
import { getRequestTracker, getConnectionTracker, getCurrentRequestId } from "./logging/index";
import { LOG_FORMAT } from "./config";
 
interface JsonSchemaProperty {
  type?: string;
  $ref?: string;
  properties?: Record<string, JsonSchemaProperty>;
  items?: JsonSchemaProperty;
  enum?: unknown[];
  oneOf?: JsonSchemaProperty[];
  anyOf?: JsonSchemaProperty[];
  [key: string]: unknown;
}
 
type JsonSchema = JsonSchemaProperty & {
  $schema?: string;
  properties?: Record<string, JsonSchemaProperty>;
};
 
/**
 * Extract HTTP status code and message from GitLab API error string
 * Matches patterns like:
 *   - "GitLab API error: 403 Forbidden - message"
 *   - "GitLab API error: 403 Forbidden"
 *   - "GitLab API error: 403"
 *   - "Failed to execute tool 'name': GitLab API error: 403 Forbidden"
 *
 * Exported for direct unit testing.
 */
export function parseGitLabApiError(
  errorMessage: string
): { status: number; message: string } | null {
  // Match GitLab API error anywhere in the string (handles wrapped errors)
  // Pattern: "GitLab API error: <status> [<statusText>] [- <details>]"
  // Status text uses [\w\s]+? to match word chars and spaces (non-greedy)
  // Separator is " - " (space-hyphen-space) to avoid matching hyphens in status text
  const match = errorMessage.match(/GitLab API error:\s*(\d+)(?:\s+([\w\s]+?))?(?:\s+-\s+(.*))?$/);
  if (!match) return null;
 
  const status = parseInt(match[1], 10);
  const statusText = match[2]?.trim() ?? "";
  const details = match[3]?.trim() ?? "";
 
  let message: string;
  if (statusText && details) {
    message = `${status} ${statusText} - ${details}`;
  } else if (statusText) {
    message = `${status} ${statusText}`;
  } else if (details) {
    message = `${status} - ${details}`;
  } else {
    message = `${status}`;
  }
 
  return { status, message };
}
 
/**
 * Type guard for objects with an action property
 */
function hasAction(value: unknown): value is { action: string } {
  return (
    typeof value === "object" &&
    value !== null &&
    "action" in value &&
    typeof (value as { action: unknown }).action === "string"
  );
}
 
/**
 * Extract action from error or its cause chain
 */
function extractActionFromError(error: unknown): string | undefined {
  Iif (hasAction(error)) {
    return error.action;
  }
 
  // Check error cause (for wrapped errors)
  const cause = (error as Error & { cause?: unknown }).cause;
  if (hasAction(cause)) {
    return cause.action;
  }
 
  return undefined;
}
 
/**
 * Check if a tool operation is idempotent (safe to retry)
 * browse_* tools are always idempotent (read-only)
 * list_*, get_*, and download_* tools are also idempotent
 */
function isIdempotentOperation(toolName: string): boolean {
  return (
    toolName.startsWith("browse_") ||
    toolName.startsWith("list_") ||
    toolName.startsWith("get_") ||
    toolName.startsWith("download_")
  );
}
 
/**
 * Convert an error to a structured GitLab error response
 * Extracts tool name and action from context, parses API errors
 */
function toStructuredError(
  error: unknown,
  toolName: string,
  toolArgs?: Record<string, unknown>
): GitLabStructuredError | null {
  // If already a structured error, return it
  Iif (isStructuredToolError(error)) {
    return error.structuredError;
  }
 
  // Check if the error cause is a structured error (for wrapped errors)
  const cause = (error as Error & { cause?: unknown }).cause;
  if (isStructuredToolError(cause)) {
    return cause.structuredError;
  }
 
  Iif (!(error instanceof Error)) return null;
 
  // Extract action early - needed for both timeout and API errors
  let action = extractActionFromError(error);
  if (!action && toolArgs && typeof toolArgs.action === "string") {
    action = toolArgs.action;
  }
  action ??= "unknown";
 
  // Check for timeout error first (before parseGitLabApiError)
  const timeoutMs = parseTimeoutError(error.message);
  if (timeoutMs !== null) {
    const retryable = isIdempotentOperation(toolName);
    return createTimeoutError(toolName, action, timeoutMs, retryable);
  }
 
  // Try to parse GitLab API error from message
  const parsed = parseGitLabApiError(error.message);
  if (!parsed) return null;
 
  return handleGitLabError(
    { status: parsed.status, message: parsed.message },
    toolName,
    action,
    toolArgs
  );
}
 
export async function setupHandlers(server: Server): Promise<void> {
  // Check if authentication is configured before trying to initialize connection
  const { isAuthenticationConfigured } = await import("./oauth/index");
 
  if (isAuthenticationConfigured()) {
    // Initialize connection and detect GitLab instance on startup
    const connectionManager = ConnectionManager.getInstance();
    try {
      await connectionManager.initialize();
      logInfo("Connection initialized during server setup");
    } catch (error) {
      logWarn(
        `Initial connection failed during setup, will retry on first tool call: ${error instanceof Error ? error.message : String(error)}`
      );
      // Continue without initialization - tools will handle gracefully on first call
    }
  } else {
    // No authentication configured - server will respond to tools/list but tool calls will fail
    logInfo("Skipping connection initialization - no authentication configured");
  }
  // List tools handler
  server.setRequestHandler(ListToolsRequestSchema, async () => {
    logInfo("ListToolsRequest received");
 
    // Get tools from registry manager (already filtered)
    const { RegistryManager } = await import("./registry-manager");
    const registryManager = RegistryManager.getInstance();
    const tools = registryManager.getAllToolDefinitions();
 
    logInfo("Returning tools list", { toolCount: tools.length });
 
    // Helper function to resolve $ref references in JSON schema
    function resolveRefs(
      schema: JsonSchemaProperty | JsonSchemaProperty[],
      rootSchema?: JsonSchema
    ): JsonSchemaProperty | JsonSchemaProperty[] {
      Iif (!schema || typeof schema !== "object") return schema;
 
      // Set root schema for reference resolution
      rootSchema ??= schema as JsonSchema;
 
      // Handle arrays
      Iif (Array.isArray(schema)) {
        return schema.map(item => resolveRefs(item, rootSchema) as JsonSchemaProperty);
      }
 
      // Handle $ref resolution
      if (schema.$ref && typeof schema.$ref === "string") {
        const refPath = schema.$ref.replace("#/properties/", "");
        const referencedProperty = rootSchema.properties?.[refPath];
 
        if (referencedProperty) {
          // Resolve the referenced property recursively
          const resolvedRef = resolveRefs(referencedProperty, rootSchema) as JsonSchemaProperty;
          // Merge with current properties (excluding $ref)
          const schemaWithoutRef = { ...schema };
          delete schemaWithoutRef.$ref;
          return { ...resolvedRef, ...schemaWithoutRef };
        }
        // If reference can't be resolved, remove $ref and keep other properties
        const schemaWithoutRef = { ...schema };
        delete schemaWithoutRef.$ref;
        return schemaWithoutRef;
      }
 
      // Recursively process all object properties
      const result: JsonSchemaProperty = {};
      for (const [key, value] of Object.entries(schema)) {
        if (key === "properties" && typeof value === "object" && value !== null) {
          // Special handling for properties object
          const resolvedProperties: Record<string, JsonSchemaProperty> = {};
          for (const [propKey, propValue] of Object.entries(
            value as Record<string, JsonSchemaProperty>
          )) {
            resolvedProperties[propKey] = resolveRefs(propValue, rootSchema) as JsonSchemaProperty;
          }
          result[key] = resolvedProperties;
        } else if (typeof value === "object" && value !== null && !Array.isArray(value)) {
          result[key] = resolveRefs(value as JsonSchemaProperty, rootSchema);
        } else {
          result[key] = value;
        }
      }
 
      return result;
    }
 
    // Remove $schema for Gemini compatibility and ensure proper JSON schema format
    const modifiedTools = tools.map(tool => {
      let inputSchema = tool.inputSchema;
 
      // Force all input schemas to be type: "object" for MCP compatibility
      Eif (inputSchema && typeof inputSchema === "object") {
        inputSchema = { ...inputSchema, type: "object" };
      }
 
      // Resolve $ref references for MCP agent compatibility
      Eif (inputSchema && typeof inputSchema === "object") {
        const resolved = resolveRefs(inputSchema);
        // Only assign if resolved is an object (not array)
        Eif (resolved && typeof resolved === "object" && !Array.isArray(resolved)) {
          inputSchema = resolved;
        }
      }
 
      // Remove $schema for Gemini compatibility
      if (inputSchema && typeof inputSchema === "object" && "$schema" in inputSchema) {
        const cleanedSchema = { ...inputSchema } as Record<string, unknown>;
        delete cleanedSchema.$schema;
        inputSchema = cleanedSchema;
      }
 
      return { ...tool, inputSchema };
    });
 
    return {
      tools: modifiedTools,
    };
  });
 
  // Call tool handler
  server.setRequestHandler(CallToolRequestSchema, async request => {
    try {
      if (!request.params.arguments) {
        throw new Error("Arguments are required");
      }
 
      // In condensed mode, tool/action is captured via request tracker for single-line log
      // In verbose mode, emit per-request INFO logs
      Iif (LOG_FORMAT === "verbose") {
        logInfo(`Tool called: ${request.params.name}`);
      }
 
      // Check if authentication is configured
      const { isOAuthEnabled, isAuthenticationConfigured } = await import("./oauth/index");
 
      if (!isAuthenticationConfigured()) {
        // No token configured - return clear error with setup instructions
        throw new Error(
          "GITLAB_TOKEN environment variable is required to execute tools. " +
            "Run 'npx @structured-world/gitlab-mcp setup' for interactive configuration, " +
            "or set GITLAB_TOKEN manually. " +
            "Documentation: https://gitlab-mcp.sw.foundation/guide/configuration"
        );
      }
 
      // Check if connection is initialized - try to initialize if needed
      const connectionManager = ConnectionManager.getInstance();
      const oauthMode = isOAuthEnabled();
 
      try {
        // Try to get client first (basic initialization check)
        connectionManager.getClient();
 
        // In OAuth mode, ensure introspection is done (uses token from context)
        Iif (oauthMode) {
          await connectionManager.ensureIntrospected();
        }
 
        const instanceInfo = connectionManager.getInstanceInfo();
        Iif (LOG_FORMAT === "verbose") {
          logInfo(`Connection verified: ${instanceInfo.version} ${instanceInfo.tier}`);
        }
      } catch {
        Iif (LOG_FORMAT === "verbose") {
          logInfo("Connection not initialized, attempting to initialize...");
        }
        try {
          await connectionManager.initialize();
          connectionManager.getClient();
 
          // In OAuth mode, ensure introspection is done after init
          Iif (oauthMode) {
            await connectionManager.ensureIntrospected();
          }
 
          const instanceInfo = connectionManager.getInstanceInfo();
          Iif (LOG_FORMAT === "verbose") {
            logInfo(`Connection initialized: ${instanceInfo.version} ${instanceInfo.tier}`);
          }
 
          // Rebuild registry cache now that tier/version info is available
          const { RegistryManager } = await import("./registry-manager");
          RegistryManager.getInstance().refreshCache();
        } catch (initError) {
          logError(
            `Connection initialization failed: ${initError instanceof Error ? initError.message : String(initError)}`
          );
          throw new Error("Bad Request: Server not initialized");
        }
      }
 
      // Dynamic tool dispatch using the new registry manager
      const toolName = request.params.name;
      const toolArgs = request.params.arguments;
      const action = toolArgs && typeof toolArgs.action === "string" ? toolArgs.action : undefined;
 
      // Access log tracking only runs in condensed mode (verbose mode uses per-line logs)
      Eif (LOG_FORMAT === "condensed") {
        const requestTracker = getRequestTracker();
        requestTracker.setToolForCurrentRequest(toolName, action);
 
        // Capture current context and read-only state for access logging
        const { getContextManager } = await import("./entities/context/context-manager");
        const contextManager = getContextManager();
        const sessionContext = contextManager.getContext();
        Iif (sessionContext.scope?.path) {
          requestTracker.setContextForCurrentRequest(sessionContext.scope.path);
        }
        requestTracker.setReadOnlyForCurrentRequest(sessionContext.readOnly);
 
        // Increment tool count for connection tracking
        const currentRequestId = getCurrentRequestId();
        Iif (currentRequestId) {
          // Get session ID from the request stack to update connection stats
          const stack = requestTracker.getStack(currentRequestId);
          if (stack?.sessionId) {
            const connectionTracker = getConnectionTracker();
            connectionTracker.incrementTools(stack.sessionId);
          }
        }
      }
 
      try {
        // Import the registry manager
        const { RegistryManager } = await import("./registry-manager");
        const registryManager = RegistryManager.getInstance();
 
        // Check if tool exists and passes all filtering (applied at registry level)
        if (!registryManager.hasToolHandler(toolName)) {
          throw new Error(`Tool '${toolName}' is not available or has been filtered out`);
        }
 
        Iif (LOG_FORMAT === "verbose") {
          logInfo(`Executing tool: ${toolName}`);
        }
 
        // Check OAuth context
        const { isOAuthEnabled, getTokenContext } = await import("./oauth/index");
        Iif (isOAuthEnabled()) {
          const context = getTokenContext();
          logDebug("OAuth context check before tool execution", {
            hasContext: !!context,
            hasToken: !!context?.gitlabToken,
            tool: toolName,
          });
        }
 
        // Execute the tool using the registry manager
        const result = await registryManager.executeTool(toolName, request.params.arguments);
 
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(result, null, 2),
            },
          ],
        };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        // Preserve original error as cause to allow action extraction and structured error detection
        throw new Error(`Failed to execute tool '${toolName}': ${errorMessage}`, { cause: error });
      }
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : String(error);
      logError(`Error in tool handler: ${errMsg}`);
 
      // Record error for access logging
      const reqTracker = getRequestTracker();
      reqTracker.setErrorForCurrentRequest(errMsg);
 
      // Record error on connection stats
      const curRequestId = getCurrentRequestId();
      Iif (curRequestId) {
        const stack = reqTracker.getStack(curRequestId);
        if (stack?.sessionId) {
          const connTracker = getConnectionTracker();
          connTracker.recordError(stack.sessionId, errMsg);
        }
      }
 
      // Try to convert to structured error for better LLM feedback
      const toolName = request.params.name;
      const toolArgs = request.params.arguments;
      const structuredError = toStructuredError(error, toolName, toolArgs);
 
      if (structuredError) {
        logDebug("Returning structured error response", { structuredError });
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(structuredError, null, 2),
            },
          ],
          isError: true,
        };
      }
 
      // Fallback to original error format
      const errorMessage = error instanceof Error ? error.message : String(error);
      return {
        content: [
          {
            type: "text",
            text: JSON.stringify({ error: errorMessage }, null, 2),
          },
        ],
        isError: true,
      };
    }
  });
}