All files / src/utils schema-utils.ts

99.4% Statements 167/168
90.9% Branches 110/121
100% Functions 16/16
100% Lines 164/164

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                                9x             9x                     9x               9x 2x 1x     1x 1x                 9x 7x                                                                             9x 1052x     1052x 1041x       11x     11x 11x   38x 38x     37x 34x 34x 18x   34x       3x 2x 2x 1x   2x     1x       11x 1x 1x       10x                           9x   40x 1x       39x 39x 39x 39x     39x 39x   39x 119x   119x   119x   820x 109x 107x 2x 2x   109x       711x 384x 384x   327x   327x 327x 16x         711x 262x 80x       449x 290x         119x       39x                           39x 384x   317x 317x 1187x 503x 503x 492x 11x 1x           317x 317x 317x 317x 493x 307x               39x 36x     39x                         6x   6x 25x 25x 25x 6x 6x       25x 6x 6x 6x 1x 1x                           9x 1316x 1316x     1316x 1316x 5x     1316x 1311x       5x     5x 1x 2x 2x     1x       4x 4x     4x                         1311x   2x     1309x                                 9x 1311x     1311x 1042x 269x   3x       1311x     1311x 1311x 30x     1311x               3x   3x 1x       2x   2x 2x 2x 8x     2x 1x 1x 1x 1x 1x           2x                   9x 992x 992x 989x     9x 3x           9x   1304x 1x       1303x 1036x 1036x 3458x 3458x 3365x 93x 1x     1036x     267x    
/**
 * Schema Utilities for Discriminated Union Transformation
 *
 * Provides functions to:
 * 1. Filter actions from discriminated union schemas
 * 2. Flatten discriminated unions to flat schemas (for AI clients)
 * 3. Apply description overrides at all levels
 *
 * Schema Pipeline:
 *   Discriminated Union (source)
 *     → Filter denied actions (remove branches)
 *     → Apply description overrides
 *     → Flatten to single object (for current AI clients)
 *     → Output JSON Schema
 */
 
import {
  GITLAB_DENIED_ACTIONS,
  GITLAB_SCHEMA_MODE,
  detectSchemaMode,
  getActionDescriptionOverrides,
  getParamDescriptionOverrides,
} from "../config";
import { logger } from "../logger";
 
// ============================================================================
// Per-Session Schema Mode (for GITLAB_SCHEMA_MODE=auto)
// ============================================================================
 
// Detected schema mode from clientInfo during initialize (used when GITLAB_SCHEMA_MODE=auto)
// NOTE: This module-level variable works correctly for stdio mode (single client per process).
// For HTTP/SSE modes with multiple concurrent sessions, this is a known limitation -
// all sessions will share the same detected mode. Use explicit GITLAB_SCHEMA_MODE for
// multi-session deployments where different clients may connect simultaneously.
let detectedSchemaMode: "flat" | "discriminated" | null = null;
 
/**
 * Set the detected schema mode based on clientInfo from MCP initialize
 * Called from server.ts oninitialized callback when GITLAB_SCHEMA_MODE=auto
 *
 * @param clientName - Client name from server.getClientVersion().name
 */
export function setDetectedSchemaMode(clientName?: string): void {
  if (GITLAB_SCHEMA_MODE !== "auto") {
    return; // Only detect when in auto mode
  }
 
  detectedSchemaMode = detectSchemaMode(clientName);
  logger.info(
    { clientName, detectedMode: detectedSchemaMode },
    "Auto-detected schema mode from client"
  );
}
 
/**
 * Clear the detected schema mode (for testing or session reset)
 */
export function clearDetectedSchemaMode(): void {
  detectedSchemaMode = null;
}
 
// ============================================================================
// Types
// ============================================================================
 
interface JSONSchemaProperty {
  type?: string;
  enum?: string[];
  const?: string;
  description?: string;
  [key: string]: unknown;
}
 
interface JSONSchema {
  type?: string;
  properties?: Record<string, JSONSchemaProperty>;
  required?: string[];
  description?: string;
  oneOf?: JSONSchema[];
  anyOf?: JSONSchema[];
  allOf?: JSONSchema[];
  discriminator?: { propertyName: string };
  $schema?: string;
  [key: string]: unknown;
}
 
// ============================================================================
// Core Transformation Functions
// ============================================================================
 
/**
 * Filter branches from a discriminated union JSON schema based on denied actions
 *
 * @param schema - JSON schema with oneOf (discriminated union)
 * @param toolName - Tool name for looking up denied actions
 * @returns Filtered schema with denied action branches removed
 */
export function filterDiscriminatedUnionActions(schema: JSONSchema, toolName: string): JSONSchema {
  const deniedActions = GITLAB_DENIED_ACTIONS.get(toolName.toLowerCase());
 
  // If no oneOf, this isn't a discriminated union - return as-is
  if (!schema.oneOf || !deniedActions || deniedActions.size === 0) {
    return schema;
  }
 
  // Deep clone to avoid mutating original
  const result = JSON.parse(JSON.stringify(schema)) as JSONSchema;
 
  // Filter oneOf branches - keep only allowed actions
  const originalOneOf = result.oneOf ?? [];
  result.oneOf = originalOneOf.filter(branch => {
    // Find the action value in this branch
    const actionProp = branch.properties?.action;
    if (!actionProp) return true; // Keep branches without action
 
    // Check if action is a const (literal)
    if (actionProp.const) {
      const isAllowed = !deniedActions.has(actionProp.const.toLowerCase());
      if (!isAllowed) {
        logger.debug(`Tool '${toolName}': filtered out action '${actionProp.const}' from schema`);
      }
      return isAllowed;
    }
 
    // Check if action is an enum with single value
    if (actionProp.enum?.[0]) {
      const isAllowed = !deniedActions.has(actionProp.enum[0].toLowerCase());
      if (!isAllowed) {
        logger.debug(`Tool '${toolName}': filtered out action '${actionProp.enum[0]}' from schema`);
      }
      return isAllowed;
    }
 
    return true; // Keep if we can't determine action
  });
 
  // If all branches filtered out, return empty schema
  if (result.oneOf.length === 0) {
    logger.warn(`Tool '${toolName}': all actions filtered out!`);
    return { type: "object", properties: {} };
  }
 
  // If only one branch left, we could simplify but keep oneOf for consistency
  return result;
}
 
/**
 * Flatten a discriminated union JSON schema to a flat object schema
 *
 * This is needed because Claude API doesn't support oneOf/anyOf at root level.
 * We merge all branches into a single object with:
 * - action: enum of all allowed actions
 * - All parameters from all branches (made optional except shared required ones)
 *
 * @param schema - JSON schema with oneOf (discriminated union)
 * @returns Flat JSON schema compatible with Claude API
 */
export function flattenDiscriminatedUnion(schema: JSONSchema): JSONSchema {
  // If no oneOf, already flat
  if (!schema.oneOf || schema.oneOf.length === 0) {
    return schema;
  }
 
  // Collect all properties and track which are shared vs branch-specific
  const allProperties: Record<string, JSONSchemaProperty> = {};
  const propertyBranches: Map<string, number> = new Map(); // prop -> count of branches using it
  const actionValues: string[] = [];
  const totalBranches = schema.oneOf.length;
 
  // Collect required properties that are required in ALL branches
  const requiredInAllBranches: Set<string> = new Set();
  let firstBranch = true;
 
  for (const branch of schema.oneOf) {
    Iif (!branch.properties) continue;
 
    const branchRequired = new Set(branch.required ?? []);
 
    for (const [propName, propDef] of Object.entries(branch.properties)) {
      // Track action values
      if (propName === "action") {
        if (propDef.const) {
          actionValues.push(propDef.const);
        } else Eif (propDef.enum) {
          actionValues.push(...propDef.enum);
        }
        continue; // Handle action separately
      }
 
      // Merge property definition
      if (!allProperties[propName]) {
        allProperties[propName] = { ...propDef };
        propertyBranches.set(propName, 1);
      } else {
        propertyBranches.set(propName, (propertyBranches.get(propName) ?? 0) + 1);
        // Merge descriptions if different (take longest)
        const existingDesc = allProperties[propName].description ?? "";
        if (propDef.description && propDef.description.length > existingDesc.length) {
          allProperties[propName].description = propDef.description;
        }
      }
 
      // Track shared required properties
      if (firstBranch) {
        if (branchRequired.has(propName)) {
          requiredInAllBranches.add(propName);
        }
      } else {
        // Remove from shared required if not required in this branch
        if (!branchRequired.has(propName)) {
          requiredInAllBranches.delete(propName);
        }
      }
    }
 
    firstBranch = false;
  }
 
  // Build flat schema
  const flatSchema: JSONSchema = {
    type: "object",
    properties: {
      action: {
        type: "string",
        enum: [...new Set(actionValues)], // Deduplicate
        description: `Action to perform: ${[...new Set(actionValues)].join(", ")}`,
      },
      ...allProperties,
    },
    required: ["action", ...Array.from(requiredInAllBranches)],
  };
 
  // Add descriptions for parameters that are only used by specific actions
  for (const [propName, count] of propertyBranches) {
    if (count < totalBranches && allProperties[propName]) {
      // This property is not in all branches - find which actions use it
      const actionsUsingProp: string[] = [];
      for (const branch of schema.oneOf) {
        if (branch.properties?.[propName]) {
          const actionProp = branch.properties.action;
          if (actionProp?.const) {
            actionsUsingProp.push(actionProp.const);
          } else if (actionProp?.enum?.[0]) {
            actionsUsingProp.push(actionProp.enum[0]);
          }
        }
      }
 
      // Append "Used by: action1, action2" to description if not already mentioned
      const propRef = flatSchema.properties?.[propName];
      Eif (propRef) {
        const currentDesc = propRef.description ?? "";
        if (actionsUsingProp.length > 0 && !currentDesc.includes("Required for")) {
          const actionList = actionsUsingProp.map(a => `'${a}'`).join(", ");
          propRef.description =
            currentDesc + (currentDesc ? " " : "") + `Required for ${actionList} action(s).`;
        }
      }
    }
  }
 
  // Copy over $schema if present
  if (schema.$schema) {
    flatSchema.$schema = schema.$schema;
  }
 
  return flatSchema;
}
 
/**
 * Apply description overrides to properties in a schema branch
 * Helper function for applyDescriptionOverrides
 */
function applyOverridesToProperties(
  properties: Record<string, JSONSchemaProperty>,
  toolName: string,
  paramOverrides: Map<string, string>,
  actionOverrides: Map<string, string>
): void {
  const lowerToolName = toolName.toLowerCase();
 
  for (const [propName, prop] of Object.entries(properties)) {
    const paramKey = `${lowerToolName}:${propName.toLowerCase()}`;
    const override = paramOverrides.get(paramKey);
    if (override) {
      prop.description = override;
      logger.debug(`Applied param override for '${toolName}.${propName}': "${override}"`);
    }
 
    // For action property, also check action-level overrides
    if (propName === "action") {
      const actionKey = `${lowerToolName}:action`;
      const actionOverride = actionOverrides.get(actionKey);
      if (actionOverride) {
        prop.description = actionOverride;
        logger.debug(`Applied action override for '${toolName}': "${actionOverride}"`);
      }
    }
  }
}
 
/**
 * Apply description overrides to a JSON schema
 * Works with both flat schemas and discriminated unions (oneOf)
 *
 * @param schema - JSON schema to modify (flat or discriminated union)
 * @param toolName - Tool name for looking up overrides
 * @returns Schema with description overrides applied
 */
export function applyDescriptionOverrides(schema: JSONSchema, toolName: string): JSONSchema {
  const actionOverrides = getActionDescriptionOverrides();
  const paramOverrides = getParamDescriptionOverrides();
 
  // Check if any overrides exist for this tool
  const lowerToolName = toolName.toLowerCase();
  const hasOverrides = [...paramOverrides.keys(), ...actionOverrides.keys()].some(key =>
    key.startsWith(`${lowerToolName}:`)
  );
 
  if (!hasOverrides) {
    return schema;
  }
 
  // Deep clone
  const result = JSON.parse(JSON.stringify(schema)) as JSONSchema;
 
  // Handle discriminated union (oneOf) - apply overrides to each branch
  if (result.oneOf) {
    for (const branch of result.oneOf) {
      Eif (branch.properties) {
        applyOverridesToProperties(branch.properties, toolName, paramOverrides, actionOverrides);
      }
    }
    return result;
  }
 
  // Handle flat schema
  Eif (result.properties) {
    applyOverridesToProperties(result.properties, toolName, paramOverrides, actionOverrides);
  }
 
  return result;
}
 
// ============================================================================
// Schema Format Configuration
// ============================================================================
 
/**
 * Get the effective schema mode
 * - If GITLAB_SCHEMA_MODE is 'flat' or 'discriminated': use that directly
 * - If GITLAB_SCHEMA_MODE is 'auto': use detected mode from clientInfo, or 'flat' as fallback
 */
function getSchemaMode(): "flat" | "discriminated" {
  if (GITLAB_SCHEMA_MODE === "auto") {
    // Use detected mode, or fall back to flat if not yet detected
    return detectedSchemaMode ?? "flat";
  }
  // Explicit mode configured
  return GITLAB_SCHEMA_MODE;
}
 
// ============================================================================
// Main Pipeline Function
// ============================================================================
 
/**
 * Transform a tool's input schema through the full pipeline:
 * 1. Filter denied actions (removes oneOf branches or enum values)
 * 2. Apply description overrides (works on oneOf branches or flat properties)
 * 3. Conditional flatten (based on GITLAB_SCHEMA_MODE config)
 *
 * @param toolName - Tool name
 * @param inputSchema - Original JSON schema (may be discriminated union or flat)
 * @returns Transformed JSON schema ready for clients
 */
export function transformToolSchema(toolName: string, inputSchema: JSONSchema): JSONSchema {
  let schema = inputSchema;
 
  // Step 1: Filter denied actions
  if (schema.oneOf) {
    schema = filterDiscriminatedUnionActions(schema, toolName);
  } else if (schema.properties?.action?.enum) {
    // Flat schema with action enum - filter the enum directly
    schema = filterFlatSchemaActions(schema, toolName);
  }
 
  // Step 2: Apply description overrides (works on oneOf or flat)
  schema = applyDescriptionOverrides(schema, toolName);
 
  // Step 3: Conditional flatten based on config
  const schemaMode = getSchemaMode();
  if (schemaMode === "flat" && schema.oneOf) {
    schema = flattenDiscriminatedUnion(schema);
  }
 
  return schema;
}
 
/**
 * Filter actions from a flat schema (legacy support)
 * Used for schemas that haven't been migrated to discriminated union yet
 */
function filterFlatSchemaActions(schema: JSONSchema, toolName: string): JSONSchema {
  const deniedActions = GITLAB_DENIED_ACTIONS.get(toolName.toLowerCase());
 
  if (!deniedActions || deniedActions.size === 0) {
    return schema;
  }
 
  // Deep clone
  const result = JSON.parse(JSON.stringify(schema)) as JSONSchema;
 
  Eif (result.properties?.action?.enum) {
    const originalActions = result.properties.action.enum;
    const filteredActions = originalActions.filter(
      action => !deniedActions.has(action.toLowerCase())
    );
 
    if (filteredActions.length === 0) {
      logger.warn(`Tool '${toolName}': all actions filtered out from flat schema!`);
    } else Eif (filteredActions.length < originalActions.length) {
      result.properties.action.enum = filteredActions;
      result.properties.action.description = `Action to perform: ${filteredActions.join(", ")}`;
      logger.debug(
        `Tool '${toolName}': filtered flat schema actions [${originalActions.join(", ")}] -> [${filteredActions.join(", ")}]`
      );
    }
  }
 
  return result;
}
 
// ============================================================================
// Utility Functions
// ============================================================================
 
/**
 * Check if all actions are denied for a tool
 */
export function shouldRemoveTool(toolName: string, allActions: string[]): boolean {
  const deniedActions = GITLAB_DENIED_ACTIONS.get(toolName.toLowerCase());
  if (!deniedActions || deniedActions.size === 0) {
    return false;
  }
 
  const allowedActions = allActions.filter(action => !deniedActions.has(action.toLowerCase()));
  return allowedActions.length === 0;
}
 
/**
 * Extract action list from a JSON schema
 */
export function extractActionsFromSchema(inputSchema: JSONSchema): string[] {
  // Check flat schema
  if (inputSchema.properties?.action?.enum) {
    return inputSchema.properties.action.enum;
  }
 
  // Check discriminated union
  if (inputSchema.oneOf) {
    const actions: string[] = [];
    for (const branch of inputSchema.oneOf) {
      const actionProp = branch.properties?.action;
      if (actionProp?.const) {
        actions.push(actionProp.const);
      } else if (actionProp?.enum?.[0]) {
        actions.push(actionProp.enum[0]);
      }
    }
    return actions;
  }
 
  return [];
}