All files / src/entities/mrs registry.ts

91.21% Statements 135/148
84.04% Branches 79/94
100% Functions 9/9
96.32% Lines 131/136

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 5123x 3x 3x         3x 3x   3x                     3x                           13x     12x       12x     3x 3x   3x       3x         5x     5x 5x 1x 5x 1x   5x 3x       2x 2x         2x 1x   1x               2x   2x 2x 2x 2x 1x 2x 1x   2x               2x   2x       2x   2x                                                   3x     3x       3x     1x 1x   1x               1x 1x             1x 1x                                                   5x     5x       5x     2x     2x 2x 7x 1x   6x       2x               2x     2x 2x 4x 2x   2x       2x               1x   1x                                                     9x     9x       9x                   2x   2x 2x 2x   2x   2x               1x   1x 1x 1x   1x                           1x   1x 1x   1x               1x   1x               2x   2x 2x 1x     2x               2x   2x     2x 1x     2x                                                     6x     6x       6x                   2x   2x 2x 2x 1x 2x   2x               1x   1x 1x   1x               1x   1x       1x         1x   1x       1x         1x   1x     1x                             3x 18x           3x 6x           3x 6x 4x 20x   2x    
import * as z from "zod";
import { BrowseMergeRequestsSchema, BrowseMrDiscussionsSchema } from "./schema-readonly";
import {
  ManageMergeRequestSchema,
  ManageMrDiscussionSchema,
  ManageDraftNotesSchema,
} from "./schema";
import { gitlab, toQuery } from "../../utils/gitlab-api";
import { normalizeProjectId } from "../../utils/projectIdentifier";
import { ToolRegistry, EnhancedToolDefinition } from "../../types";
import { isActionDenied } from "../../config";
 
/**
 * MRS (Merge Requests) tools registry - 5 CQRS tools replacing 20 individual tools
 *
 * browse_merge_requests (Query): list, get, diffs, compare
 * browse_mr_discussions (Query): list, drafts, draft
 * manage_merge_request (Command): create, update, merge
 * manage_mr_discussion (Command): comment, thread, reply, update, apply_suggestion, apply_suggestions
 * manage_draft_notes (Command): create, update, publish, publish_all, delete
 */
export const mrsToolRegistry: ToolRegistry = new Map<string, EnhancedToolDefinition>([
  // ============================================================================
  // browse_merge_requests - CQRS Query Tool (discriminated union schema)
  // TypeScript automatically narrows types in each switch case
  // ============================================================================
  [
    "browse_merge_requests",
    {
      name: "browse_merge_requests",
      description:
        'BROWSE merge requests. Actions: "list" shows MRs with filtering, "get" retrieves single MR by IID or branch, "diffs" shows file changes, "compare" diffs two branches/commits.',
      inputSchema: z.toJSONSchema(BrowseMergeRequestsSchema),
      gate: { envVar: "USE_MRS", defaultValue: true },
      handler: async (args: unknown) => {
        const input = BrowseMergeRequestsSchema.parse(args);
 
        // Runtime validation: reject denied actions even if they bypass schema filtering
        Iif (isActionDenied("browse_merge_requests", input.action)) {
          throw new Error(`Action '${input.action}' is not allowed for browse_merge_requests tool`);
        }
 
        switch (input.action) {
          case "list": {
            // TypeScript knows: input has state, order_by, sort, milestone, etc. (all optional)
            const { action: _action, project_id, ...rest } = input;
            const query = toQuery(rest, []);
 
            const path = project_id
              ? `projects/${normalizeProjectId(project_id)}/merge_requests`
              : `merge_requests`;
 
            return gitlab.get(path, { query });
          }
 
          case "get": {
            // TypeScript knows: input has project_id (required), merge_request_iid (optional), branch_name (optional)
            const { project_id, merge_request_iid, branch_name } = input;
 
            // Build query params for optional fields
            const query: Record<string, boolean | string | undefined> = {};
            if (input.include_diverged_commits_count !== undefined)
              query.include_diverged_commits_count = input.include_diverged_commits_count;
            if (input.include_rebase_in_progress !== undefined)
              query.include_rebase_in_progress = input.include_rebase_in_progress;
 
            if (merge_request_iid) {
              return gitlab.get(
                `projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}`,
                Object.keys(query).length > 0 ? { query } : undefined
              );
            } else Eif (branch_name) {
              const result = await gitlab.get<unknown[]>(
                `projects/${normalizeProjectId(project_id)}/merge_requests`,
                { query: { source_branch: branch_name, ...query } }
              );
 
              if (Array.isArray(result) && result.length > 0) {
                return result[0];
              }
              throw new Error("No merge request found for branch");
            }
            /* istanbul ignore next -- unreachable: schema validation ensures merge_request_iid or branch_name */
            throw new Error("Either merge_request_iid or branch_name must be provided");
          }
 
          case "diffs": {
            // TypeScript knows: input has project_id (required), merge_request_iid (required)
            const { project_id, merge_request_iid } = input;
 
            const query: Record<string, number | boolean | undefined> = {};
            if (input.page !== undefined) query.page = input.page;
            if (input.per_page !== undefined) query.per_page = input.per_page;
            if (input.include_diverged_commits_count !== undefined)
              query.include_diverged_commits_count = input.include_diverged_commits_count;
            if (input.include_rebase_in_progress !== undefined)
              query.include_rebase_in_progress = input.include_rebase_in_progress;
 
            return gitlab.get(
              `projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/changes`,
              { query }
            );
          }
 
          case "compare": {
            // TypeScript knows: input has project_id (required), from (required), to (required)
            const { project_id, from, to, straight } = input;
 
            const query: Record<string, string | boolean | undefined> = {
              from,
              to,
            };
            if (straight !== undefined) query.straight = straight;
 
            return gitlab.get(`projects/${normalizeProjectId(project_id)}/repository/compare`, {
              query,
            });
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
 
  // ============================================================================
  // browse_mr_discussions - CQRS Query Tool (discriminated union schema)
  // TypeScript automatically narrows types in each switch case
  // ============================================================================
  [
    "browse_mr_discussions",
    {
      name: "browse_mr_discussions",
      description:
        'BROWSE MR discussions and draft notes. Actions: "list" shows all discussion threads, "drafts" lists unpublished draft notes, "draft" gets single draft note.',
      inputSchema: z.toJSONSchema(BrowseMrDiscussionsSchema),
      gate: { envVar: "USE_MRS", defaultValue: true },
      handler: async (args: unknown) => {
        const input = BrowseMrDiscussionsSchema.parse(args);
 
        // Runtime validation: reject denied actions even if they bypass schema filtering
        Iif (isActionDenied("browse_mr_discussions", input.action)) {
          throw new Error(`Action '${input.action}' is not allowed for browse_mr_discussions tool`);
        }
 
        switch (input.action) {
          case "list": {
            // TypeScript knows: input has project_id (required), merge_request_iid (required), per_page, page (optional)
            const { action: _action, project_id, merge_request_iid, ...rest } = input;
            const query = toQuery(rest, []);
 
            return gitlab.get(
              `projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/discussions`,
              { query }
            );
          }
 
          case "drafts": {
            // TypeScript knows: input has project_id (required), merge_request_iid (required)
            const { project_id, merge_request_iid } = input;
            return gitlab.get(
              `projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/draft_notes`
            );
          }
 
          case "draft": {
            // TypeScript knows: input has project_id (required), merge_request_iid (required), draft_note_id (required)
            const { project_id, merge_request_iid, draft_note_id } = input;
            return gitlab.get(
              `projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/draft_notes/${draft_note_id}`
            );
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
 
  // ============================================================================
  // manage_merge_request - CQRS Command Tool (discriminated union schema)
  // TypeScript automatically narrows types in each switch case
  // ============================================================================
  [
    "manage_merge_request",
    {
      name: "manage_merge_request",
      description:
        'MANAGE merge requests. Actions: "create" creates new MR, "update" modifies existing MR, "merge" merges approved MR into target branch.',
      inputSchema: z.toJSONSchema(ManageMergeRequestSchema),
      gate: { envVar: "USE_MRS", defaultValue: true },
      handler: async (args: unknown) => {
        const input = ManageMergeRequestSchema.parse(args);
 
        // Runtime validation: reject denied actions even if they bypass schema filtering
        Iif (isActionDenied("manage_merge_request", input.action)) {
          throw new Error(`Action '${input.action}' is not allowed for manage_merge_request tool`);
        }
 
        switch (input.action) {
          case "create": {
            // TypeScript knows: input has source_branch (required), target_branch (required), title (required)
            const { action: _action, project_id, ...body } = input;
 
            // Handle array fields - convert to comma-separated strings for form encoding
            const processedBody: Record<string, unknown> = {};
            for (const [key, value] of Object.entries(body)) {
              if (Array.isArray(value)) {
                processedBody[key] = value.join(",");
              } else {
                processedBody[key] = value;
              }
            }
 
            return gitlab.post(`projects/${normalizeProjectId(project_id)}/merge_requests`, {
              body: processedBody,
              contentType: "form",
            });
          }
 
          case "update": {
            // TypeScript knows: input has merge_request_iid (required)
            const { action: _action, project_id, merge_request_iid, ...body } = input;
 
            // Handle array fields
            const processedBody: Record<string, unknown> = {};
            for (const [key, value] of Object.entries(body)) {
              if (Array.isArray(value)) {
                processedBody[key] = value.join(",");
              } else {
                processedBody[key] = value;
              }
            }
 
            return gitlab.put(
              `projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}`,
              { body: processedBody, contentType: "form" }
            );
          }
 
          case "merge": {
            // TypeScript knows: input has merge_request_iid (required)
            const { action: _action, project_id, merge_request_iid, ...body } = input;
 
            return gitlab.put(
              `projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/merge`,
              { body, contentType: "form" }
            );
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
 
  // ============================================================================
  // manage_mr_discussion - CQRS Command Tool (discriminated union schema)
  // TypeScript automatically narrows types in each switch case
  // ============================================================================
  [
    "manage_mr_discussion",
    {
      name: "manage_mr_discussion",
      description:
        'MANAGE MR discussions and suggestions. Actions: "comment" adds comment, "thread" starts discussion, "reply" responds to thread, "update" modifies note, "apply_suggestion" applies single code suggestion, "apply_suggestions" batch applies multiple suggestions.',
      inputSchema: z.toJSONSchema(ManageMrDiscussionSchema),
      gate: { envVar: "USE_MRS", defaultValue: true },
      handler: async (args: unknown) => {
        const input = ManageMrDiscussionSchema.parse(args);
 
        // Runtime validation: reject denied actions even if they bypass schema filtering
        Iif (isActionDenied("manage_mr_discussion", input.action)) {
          throw new Error(`Action '${input.action}' is not allowed for manage_mr_discussion tool`);
        }
 
        switch (input.action) {
          case "comment": {
            // TypeScript knows: input has noteable_type (required), noteable_id (required), body (required)
            const {
              project_id,
              noteable_type,
              noteable_id,
              body: noteBody,
              created_at,
              confidential,
            } = input;
 
            const body: Record<string, unknown> = { body: noteBody };
            Iif (created_at) body.created_at = created_at;
            Iif (confidential !== undefined) body.confidential = confidential;
 
            const resourceType = noteable_type === "merge_request" ? "merge_requests" : "issues";
 
            return gitlab.post(
              `projects/${normalizeProjectId(project_id)}/${resourceType}/${noteable_id}/notes`,
              { body, contentType: "form" }
            );
          }
 
          case "thread": {
            // TypeScript knows: input has merge_request_iid (required), body (required)
            const { project_id, merge_request_iid, body: noteBody, position, commit_id } = input;
 
            const body: Record<string, unknown> = { body: noteBody };
            Iif (position) body.position = JSON.stringify(position);
            Iif (commit_id) body.commit_id = commit_id;
 
            return gitlab.post(
              `projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/discussions`,
              { body, contentType: "form" }
            );
          }
 
          case "reply": {
            // TypeScript knows: input has merge_request_iid (required), discussion_id (required), body (required)
            const {
              project_id,
              merge_request_iid,
              discussion_id,
              body: noteBody,
              created_at,
            } = input;
 
            const body: Record<string, unknown> = { body: noteBody };
            Iif (created_at) body.created_at = created_at;
 
            return gitlab.post(
              `projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/discussions/${discussion_id}/notes`,
              { body, contentType: "form" }
            );
          }
 
          case "update": {
            // TypeScript knows: input has merge_request_iid (required), note_id (required), body (required)
            const { project_id, merge_request_iid, note_id, body: noteBody } = input;
 
            return gitlab.put(
              `projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/notes/${note_id}`,
              { body: { body: noteBody }, contentType: "form" }
            );
          }
 
          case "apply_suggestion": {
            // TypeScript knows: input has suggestion_id (required), commit_message (optional)
            const { project_id, merge_request_iid, suggestion_id, commit_message } = input;
 
            const body: Record<string, unknown> = {};
            if (commit_message) {
              body.commit_message = commit_message;
            }
 
            return gitlab.put(
              `projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/suggestions/${suggestion_id}/apply`,
              { body: Object.keys(body).length > 0 ? body : undefined, contentType: "json" }
            );
          }
 
          case "apply_suggestions": {
            // TypeScript knows: input has suggestion_ids (required), commit_message (optional)
            const { project_id, merge_request_iid, suggestion_ids, commit_message } = input;
 
            const body: Record<string, unknown> = {
              ids: suggestion_ids,
            };
            if (commit_message) {
              body.commit_message = commit_message;
            }
 
            return gitlab.put(
              `projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/suggestions/batch_apply`,
              { body, contentType: "json" }
            );
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
 
  // ============================================================================
  // manage_draft_notes - CQRS Command Tool (discriminated union schema)
  // TypeScript automatically narrows types in each switch case
  // ============================================================================
  [
    "manage_draft_notes",
    {
      name: "manage_draft_notes",
      description:
        'MANAGE draft notes. Actions: "create" creates draft note, "update" modifies draft, "publish" publishes single draft, "publish_all" publishes all drafts, "delete" removes draft.',
      inputSchema: z.toJSONSchema(ManageDraftNotesSchema),
      gate: { envVar: "USE_MRS", defaultValue: true },
      handler: async (args: unknown) => {
        const input = ManageDraftNotesSchema.parse(args);
 
        // Runtime validation: reject denied actions even if they bypass schema filtering
        Iif (isActionDenied("manage_draft_notes", input.action)) {
          throw new Error(`Action '${input.action}' is not allowed for manage_draft_notes tool`);
        }
 
        switch (input.action) {
          case "create": {
            // TypeScript knows: input has note (required), position, in_reply_to_discussion_id, commit_id (optional)
            const {
              project_id,
              merge_request_iid,
              note,
              position,
              in_reply_to_discussion_id,
              commit_id,
            } = input;
 
            const body: Record<string, unknown> = { note };
            Iif (position) body.position = JSON.stringify(position);
            if (in_reply_to_discussion_id)
              body.in_reply_to_discussion_id = in_reply_to_discussion_id;
            Iif (commit_id) body.commit_id = commit_id;
 
            return gitlab.post(
              `projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/draft_notes`,
              { body, contentType: "form" }
            );
          }
 
          case "update": {
            // TypeScript knows: input has draft_note_id (required), note (required)
            const { project_id, merge_request_iid, draft_note_id, note, position } = input;
 
            const body: Record<string, unknown> = { note };
            Iif (position) body.position = JSON.stringify(position);
 
            return gitlab.put(
              `projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/draft_notes/${draft_note_id}`,
              { body, contentType: "form" }
            );
          }
 
          case "publish": {
            // TypeScript knows: input has draft_note_id (required)
            const { project_id, merge_request_iid, draft_note_id } = input;
 
            const result = await gitlab.put<void>(
              `projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/draft_notes/${draft_note_id}/publish`
            );
            // PUT publish returns 204 No Content (undefined) on success
            return result ?? { published: true };
          }
 
          case "publish_all": {
            // TypeScript knows: input has project_id (required), merge_request_iid (required)
            const { project_id, merge_request_iid } = input;
 
            const result = await gitlab.post<void>(
              `projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/draft_notes/bulk_publish`
            );
            // POST bulk_publish returns 204 No Content (undefined) on success
            return result ?? { published: true };
          }
 
          case "delete": {
            // TypeScript knows: input has draft_note_id (required)
            const { project_id, merge_request_iid, draft_note_id } = input;
 
            await gitlab.delete<void>(
              `projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/draft_notes/${draft_note_id}`
            );
            return { success: true, message: "Draft note deleted successfully" };
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
]);
 
/**
 * Get read-only tool names from the registry
 */
export function getMrsReadOnlyToolNames(): string[] {
  return ["browse_merge_requests", "browse_mr_discussions"];
}
 
/**
 * Get all tool definitions from the registry
 */
export function getMrsToolDefinitions(): EnhancedToolDefinition[] {
  return Array.from(mrsToolRegistry.values());
}
 
/**
 * Get filtered tools based on read-only mode
 */
export function getFilteredMrsTools(readOnlyMode: boolean = false): EnhancedToolDefinition[] {
  if (readOnlyMode) {
    const readOnlyNames = getMrsReadOnlyToolNames();
    return Array.from(mrsToolRegistry.values()).filter(tool => readOnlyNames.includes(tool.name));
  }
  return getMrsToolDefinitions();
}