All files / src/entities/mrs registry.ts

88.75% Statements 213/240
71.05% Branches 81/114
100% Functions 30/30
88.7% Lines 212/239

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 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768  3x 3x                   3x                           3x 3x 3x           3x                   3x 3x   3x 3x 1x     3x 3x           3x 1x     2x 2x                       6x 5x       5x   3x 2x   2x         5x           4x       3x   3x   2x 1x   1x       1x                       3x   3x 3x 7x 5x         3x       3x           3x 1x     2x 2x                       1x 1x   1x 1x 1x   1x 1x     1x 1x           1x       1x 1x                       1x 1x   1x 1x 1x   1x 1x     1x 1x           1x       1x 1x                       1x 1x   1x 1x 3x 1x       1x 1x           1x       1x 1x                       1x 1x   1x 1x           1x       1x 1x                       1x 1x   1x 1x 2x         1x 1x           1x       1x 1x                         2x   2x 2x 9x 9x 1x   8x         2x 2x                 2x       2x 2x                       1x   1x 1x 4x 2x       1x 1x                 1x       1x 1x                       2x   2x 2x 2x     2x         2x 2x   2x 2x                 2x       2x 2x                       1x   1x 1x 1x       1x 1x                 1x       1x 1x                       1x   1x 1x             1x       1x 1x                       1x   1x 1x             1x       1x 1x                       1x   1x 1x 6x 4x 1x   3x         1x 1x                 1x       1x 1x                       1x   1x 1x 1x     1x       1x 1x                 1x       1x 1x                       1x   1x 1x   1x 1x                 1x       1x 1x                       1x   1x 1x 1x       1x 1x                 1x       1x 1x                       1x   1x 1x 1x       1x 1x                 1x       1x 1x                       1x   1x 1x             1x       1x                 3x 18x                             3x 6x           3x 7x 5x 100x   2x    
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { zodToJsonSchema } from "zod-to-json-schema";
import {
  GetBranchDiffsSchema,
  GetMergeRequestSchema,
  GetMergeRequestDiffsSchema,
  ListMergeRequestDiffsSchema,
  ListMergeRequestDiscussionsSchema,
  GetDraftNoteSchema,
  ListDraftNotesSchema,
  ListMergeRequestsSchema,
} from "./schema-readonly";
import {
  CreateMergeRequestSchema,
  UpdateMergeRequestSchema,
  MergeMergeRequestSchema,
  CreateNoteSchema,
  CreateMergeRequestThreadSchema,
  UpdateMergeRequestNoteSchema,
  CreateMergeRequestNoteSchema,
  CreateDraftNoteSchema,
  UpdateDraftNoteSchema,
  DeleteDraftNoteSchema,
  PublishDraftNoteSchema,
  BulkPublishDraftNotesSchema,
} from "./schema";
import { enhancedFetch } from "../../utils/fetch";
import { normalizeProjectId } from "../../utils/projectIdentifier";
import { cleanGidsFromObject } from "../../utils/idConversion";
import { ToolRegistry, EnhancedToolDefinition } from "../../types";
 
/**
 * MRS (Merge Requests) tools registry - unified registry containing all MR tools with their handlers
 */
export const mrsToolRegistry: ToolRegistry = new Map<string, EnhancedToolDefinition>([
  // Read-only tools
  [
    "get_branch_diffs",
    {
      name: "get_branch_diffs",
      description:
        "COMPARE: Get diffs between two branches or commits in a GitLab project. Use when: Reviewing changes before merging, Analyzing code differences, Generating change reports. Supports both direct comparison and merge-base comparison methods.",
      inputSchema: zodToJsonSchema(GetBranchDiffsSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = GetBranchDiffsSchema.parse(args);
        const { project_id, from, to, straight } = options;
 
        const queryParams = new URLSearchParams();
        if (straight !== undefined) {
          queryParams.set("straight", String(straight));
        }
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${normalizeProjectId(project_id)}/repository/compare?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}&${queryParams}`;
        const response = await enhancedFetch(apiUrl, {
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
          },
        });
 
        if (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const diff = await response.json();
        return cleanGidsFromObject(diff);
      },
    },
  ],
  [
    "get_merge_request",
    {
      name: "get_merge_request",
      description:
        "READ: Get comprehensive details of a merge request including status, discussions, and approvals. Use when: Reviewing MR details, Checking merge status, Gathering information for automation. Accepts either MR IID or source branch name for flexibility.",
      inputSchema: zodToJsonSchema(GetMergeRequestSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = GetMergeRequestSchema.parse(args);
        const { project_id, merge_request_iid, branch_name } = options;
 
        let apiUrl: string;
 
        if (merge_request_iid) {
          // Get specific MR by IID
          apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}`;
        } else if (branch_name) {
          // Search for MR by source branch
          apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${normalizeProjectId(project_id)}/merge_requests?source_branch=${encodeURIComponent(branch_name)}`;
        } else E{
          throw new Error("Either merge_request_iid or branch_name must be provided");
        }
 
        const response = await enhancedFetch(apiUrl, {
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
          },
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const result = await response.json();
 
        if (branch_name) {
          // When searching by branch, return the first MR found
          if (Array.isArray(result) && result.length > 0) {
            return result[0];
          } else {
            throw new Error("No merge request found for branch");
          }
        }
 
        return cleanGidsFromObject(result);
      },
    },
  ],
  [
    "list_merge_requests",
    {
      name: "list_merge_requests",
      description:
        "BROWSE: List merge requests in a GitLab project with extensive filtering capabilities. Use when: Finding MRs by state/author/assignee, Complex queries for MR management, Reporting on merge requests. Can search globally or within specific projects.",
      inputSchema: zodToJsonSchema(ListMergeRequestsSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = ListMergeRequestsSchema.parse(args);
 
        const queryParams = new URLSearchParams();
        Object.entries(options).forEach(([key, value]) => {
          if (value !== undefined && value !== null && key !== "project_id") {
            queryParams.set(key, String(value));
          }
        });
 
        // Handle optional project_id - use global endpoint if not provided
        const apiUrl = options.project_id
          ? `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(options.project_id)}/merge_requests?${queryParams}`
          : `${process.env.GITLAB_API_URL}/api/v4/merge_requests?${queryParams}`;
 
        const response = await enhancedFetch(apiUrl, {
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
          },
        });
 
        if (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const mergeRequests = await response.json();
        return cleanGidsFromObject(mergeRequests);
      },
    },
  ],
  [
    "get_merge_request_diffs",
    {
      name: "get_merge_request_diffs",
      description:
        "READ: Get all file changes and diffs included in a merge request. Use when: Reviewing code changes, Analyzing modifications, Automating code review processes. Shows actual file differences that would be applied if merged.",
      inputSchema: zodToJsonSchema(GetMergeRequestDiffsSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = GetMergeRequestDiffsSchema.parse(args);
        const { project_id, merge_request_iid, page, per_page } = options;
 
        const queryParams = new URLSearchParams();
        Eif (page !== undefined) {
          queryParams.set("page", String(page));
        }
        Eif (per_page !== undefined) {
          queryParams.set("per_page", String(per_page));
        }
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/changes?${queryParams}`;
        const response = await enhancedFetch(apiUrl, {
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
          },
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const diffs = await response.json();
        return cleanGidsFromObject(diffs);
      },
    },
  ],
  [
    "list_merge_request_diffs",
    {
      name: "list_merge_request_diffs",
      description:
        "BROWSE: List all diffs in a merge request with pagination for large changesets. Use when: Dealing with MRs containing many changes, Managing memory usage, Processing large diffs efficiently. Provides paginated access to file modifications.",
      inputSchema: zodToJsonSchema(ListMergeRequestDiffsSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = ListMergeRequestDiffsSchema.parse(args);
        const { project_id, merge_request_iid, page, per_page } = options;
 
        const queryParams = new URLSearchParams();
        Eif (page !== undefined) {
          queryParams.set("page", String(page));
        }
        Eif (per_page !== undefined) {
          queryParams.set("per_page", String(per_page));
        }
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/diffs?${queryParams}`;
        const response = await enhancedFetch(apiUrl, {
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
          },
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const diffs = await response.json();
        return cleanGidsFromObject(diffs);
      },
    },
  ],
  [
    "mr_discussions",
    {
      name: "mr_discussions",
      description:
        "DISCUSS: List all discussion threads and comments on a merge request. Use when: Tracking code review feedback, Managing conversations, Extracting review insights. Includes both resolved and unresolved discussions with full context.",
      inputSchema: zodToJsonSchema(ListMergeRequestDiscussionsSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = ListMergeRequestDiscussionsSchema.parse(args);
        const { project_id, merge_request_iid } = options;
 
        const queryParams = new URLSearchParams();
        Object.entries(options).forEach(([key, value]) => {
          if (value !== undefined && key !== "project_id" && key !== "merge_request_iid") {
            queryParams.set(key, String(value));
          }
        });
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/discussions?${queryParams}`;
        const response = await enhancedFetch(apiUrl, {
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
          },
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const discussions = await response.json();
        return cleanGidsFromObject(discussions);
      },
    },
  ],
  [
    "get_draft_note",
    {
      name: "get_draft_note",
      description:
        "DRAFT: Retrieve a specific draft note (unpublished comment) from a merge request. Use when: Reviewing pending feedback before publishing, Managing draft review comments. Draft notes are only visible to their author until published.",
      inputSchema: zodToJsonSchema(GetDraftNoteSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = GetDraftNoteSchema.parse(args);
        const { project_id, merge_request_iid, draft_note_id } = options;
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/draft_notes/${draft_note_id}`;
        const response = await enhancedFetch(apiUrl, {
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
          },
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const draftNote = await response.json();
        return cleanGidsFromObject(draftNote);
      },
    },
  ],
  [
    "list_draft_notes",
    {
      name: "list_draft_notes",
      description:
        "DRAFT: List all draft notes (unpublished comments) for a merge request. Use when: Reviewing all pending feedback before publishing, Managing batch review comments. Draft notes allow reviewers to prepare comprehensive feedback before sharing.",
      inputSchema: zodToJsonSchema(ListDraftNotesSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = ListDraftNotesSchema.parse(args);
        const { project_id, merge_request_iid } = options;
 
        const queryParams = new URLSearchParams();
        Object.entries(options).forEach(([key, value]) => {
          Iif (value !== undefined && key !== "project_id" && key !== "merge_request_iid") {
            queryParams.set(key, String(value));
          }
        });
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${normalizeProjectId(project_id)}/merge_requests/${merge_request_iid}/draft_notes?${queryParams}`;
        const response = await enhancedFetch(apiUrl, {
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
          },
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const draftNotes = await response.json();
        return cleanGidsFromObject(draftNotes);
      },
    },
  ],
  // Write tools
  [
    "create_merge_request",
    {
      name: "create_merge_request",
      description:
        "CREATE: Create a new merge request to propose code changes for review and merging. Use when: Initiating code review process, Proposing features, Submitting fixes. For labels: Use list_labels FIRST to discover existing project taxonomy. Requires source and target branches, supports setting assignees, reviewers, and labels.",
      inputSchema: zodToJsonSchema(CreateMergeRequestSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = CreateMergeRequestSchema.parse(args);
 
        const body = new URLSearchParams();
        Object.entries(options).forEach(([key, value]) => {
          Eif (value !== undefined && value !== null) {
            if (Array.isArray(value)) {
              body.set(key, value.join(","));
            } else {
              body.set(key, String(value));
            }
          }
        });
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(options.project_id)}/merge_requests`;
        const response = await enhancedFetch(apiUrl, {
          method: "POST",
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: body.toString(),
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const mergeRequest = await response.json();
        return cleanGidsFromObject(mergeRequest);
      },
    },
  ],
  [
    "merge_merge_request",
    {
      name: "merge_merge_request",
      description:
        "MERGE: Merge an approved merge request into the target branch. Use when: Completing the code review process, Integrating changes. Supports various merge methods (merge commit, squash, rebase) and can delete source branch after merging.",
      inputSchema: zodToJsonSchema(MergeMergeRequestSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = MergeMergeRequestSchema.parse(args);
 
        const body = new URLSearchParams();
        Object.entries(options).forEach(([key, value]) => {
          if (value !== undefined && key !== "project_id" && key !== "merge_request_iid") {
            body.set(key, String(value));
          }
        });
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(options.project_id)}/merge_requests/${options.merge_request_iid}/merge`;
        const response = await enhancedFetch(apiUrl, {
          method: "PUT",
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: body.toString(),
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const result = await response.json();
        return cleanGidsFromObject(result);
      },
    },
  ],
  [
    "create_note",
    {
      name: "create_note",
      description:
        "COMMENT: Add a comment to an issue or merge request for discussion or feedback. Use when: Providing code review comments, Asking questions, Documenting decisions. Supports markdown formatting and can trigger notifications to participants.",
      inputSchema: zodToJsonSchema(CreateNoteSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = CreateNoteSchema.parse(args);
 
        const body = new URLSearchParams();
        body.set("body", options.body);
        Iif (options.created_at) {
          body.set("created_at", options.created_at);
        }
        Iif (options.confidential !== undefined) {
          body.set("confidential", String(options.confidential));
        }
 
        const resourceType =
          options.noteable_type === "merge_request" ? "merge_requests" : "issues";
        const resourceId = options.noteable_id;
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(options.project_id)}/${resourceType}/${resourceId}/notes`;
        const response = await enhancedFetch(apiUrl, {
          method: "POST",
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: body.toString(),
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const note = await response.json();
        return cleanGidsFromObject(note);
      },
    },
  ],
  [
    "create_draft_note",
    {
      name: "create_draft_note",
      description:
        "DRAFT: Create a draft note (unpublished comment) on a merge request. Use when: Preparing review feedback that can be refined before publishing. Draft notes are ideal for comprehensive reviews where all comments are published together.",
      inputSchema: zodToJsonSchema(CreateDraftNoteSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = CreateDraftNoteSchema.parse(args);
 
        const body = new URLSearchParams();
        body.set("note", options.note);
        Iif (options.position) {
          body.set("position", JSON.stringify(options.position));
        }
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(options.project_id)}/merge_requests/${options.merge_request_iid}/draft_notes`;
        const response = await enhancedFetch(apiUrl, {
          method: "POST",
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: body.toString(),
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const draftNote = await response.json();
        return cleanGidsFromObject(draftNote);
      },
    },
  ],
  [
    "publish_draft_note",
    {
      name: "publish_draft_note",
      description:
        "DRAFT: Publish a previously created draft note to make it visible to all participants. Use when: Selectively sharing specific review comments when ready. Once published, the note becomes a regular comment and triggers notifications.",
      inputSchema: zodToJsonSchema(PublishDraftNoteSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = PublishDraftNoteSchema.parse(args);
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(options.project_id)}/merge_requests/${options.merge_request_iid}/draft_notes/${options.draft_note_id}/publish`;
        const response = await enhancedFetch(apiUrl, {
          method: "PUT",
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
          },
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const result = await response.json();
        return cleanGidsFromObject(result);
      },
    },
  ],
  [
    "bulk_publish_draft_notes",
    {
      name: "bulk_publish_draft_notes",
      description:
        "Publish all pending draft notes for a merge request simultaneously. Use to share comprehensive review feedback in one action. Ideal for thorough code reviews where all comments should be seen together for context.",
      inputSchema: zodToJsonSchema(BulkPublishDraftNotesSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = BulkPublishDraftNotesSchema.parse(args);
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(options.project_id)}/merge_requests/${options.merge_request_iid}/draft_notes/bulk_publish`;
        const response = await enhancedFetch(apiUrl, {
          method: "POST",
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
          },
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const result = await response.json();
        return cleanGidsFromObject(result);
      },
    },
  ],
  [
    "update_merge_request",
    {
      name: "update_merge_request",
      description:
        "UPDATE: Update properties of an existing merge request such as title, description, or assignees. Use when: Refining MR details, Changing reviewers, Updating labels. For labels: Use list_labels FIRST to discover existing taxonomy before updating. Accepts either MR IID or source branch name for identification.",
      inputSchema: zodToJsonSchema(UpdateMergeRequestSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = UpdateMergeRequestSchema.parse(args);
 
        const body = new URLSearchParams();
        Object.entries(options).forEach(([key, value]) => {
          if (value !== undefined && key !== "project_id" && key !== "merge_request_iid") {
            if (Array.isArray(value)) {
              body.set(key, value.join(","));
            } else {
              body.set(key, String(value));
            }
          }
        });
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(options.project_id)}/merge_requests/${options.merge_request_iid}`;
        const response = await enhancedFetch(apiUrl, {
          method: "PUT",
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: body.toString(),
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const mergeRequest = await response.json();
        return cleanGidsFromObject(mergeRequest);
      },
    },
  ],
  [
    "create_merge_request_thread",
    {
      name: "create_merge_request_thread",
      description:
        "Start a new discussion thread on a merge request for focused conversation. Use to raise specific concerns, ask questions about code sections, or initiate design discussions. Threads can be resolved when addressed.",
      inputSchema: zodToJsonSchema(CreateMergeRequestThreadSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = CreateMergeRequestThreadSchema.parse(args);
 
        const body = new URLSearchParams();
        body.set("body", options.body);
        Iif (options.position) {
          body.set("position", JSON.stringify(options.position));
        }
        Iif (options.commit_id) {
          body.set("commit_id", options.commit_id);
        }
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(options.project_id)}/merge_requests/${options.merge_request_iid}/discussions`;
        const response = await enhancedFetch(apiUrl, {
          method: "POST",
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: body.toString(),
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const discussion = await response.json();
        return cleanGidsFromObject(discussion);
      },
    },
  ],
  [
    "update_merge_request_note",
    {
      name: "update_merge_request_note",
      description:
        "Edit an existing comment within a merge request discussion thread. Use to correct mistakes, clarify points, or update information in previous comments. Maintains discussion history while allowing content refinement.",
      inputSchema: zodToJsonSchema(UpdateMergeRequestNoteSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = UpdateMergeRequestNoteSchema.parse(args);
 
        const body = new URLSearchParams();
        body.set("body", options.body);
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(options.project_id)}/merge_requests/${options.merge_request_iid}/notes/${options.note_id}`;
        const response = await enhancedFetch(apiUrl, {
          method: "PUT",
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: body.toString(),
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const note = await response.json();
        return cleanGidsFromObject(note);
      },
    },
  ],
  [
    "create_merge_request_note",
    {
      name: "create_merge_request_note",
      description:
        "Reply to an existing discussion thread in a merge request. Use to continue conversations, provide answers, or add context to ongoing discussions. Keeps related comments organized in threaded format.",
      inputSchema: zodToJsonSchema(CreateMergeRequestNoteSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = CreateMergeRequestNoteSchema.parse(args);
 
        const body = new URLSearchParams();
        body.set("body", options.body);
        Iif (options.created_at) {
          body.set("created_at", options.created_at);
        }
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(options.project_id)}/merge_requests/${options.merge_request_iid}/discussions/${options.discussion_id}/notes`;
        const response = await enhancedFetch(apiUrl, {
          method: "POST",
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: body.toString(),
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const note = await response.json();
        return cleanGidsFromObject(note);
      },
    },
  ],
  [
    "update_draft_note",
    {
      name: "update_draft_note",
      description:
        "Modify a draft note before publishing to refine review feedback. Use to edit, improve, or correct draft comments based on further code examination. Changes are only visible to the author until the note is published.",
      inputSchema: zodToJsonSchema(UpdateDraftNoteSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = UpdateDraftNoteSchema.parse(args);
 
        const body = new URLSearchParams();
        body.set("note", options.note);
        Iif (options.position) {
          body.set("position", JSON.stringify(options.position));
        }
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(options.project_id)}/merge_requests/${options.merge_request_iid}/draft_notes/${options.draft_note_id}`;
        const response = await enhancedFetch(apiUrl, {
          method: "PUT",
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: body.toString(),
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const draftNote = await response.json();
        return cleanGidsFromObject(draftNote);
      },
    },
  ],
  [
    "delete_draft_note",
    {
      name: "delete_draft_note",
      description:
        "Remove a draft note that is no longer needed or relevant. Use to clean up draft feedback that won't be published or to start fresh with review comments. Only the author can delete their own draft notes.",
      inputSchema: zodToJsonSchema(DeleteDraftNoteSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = DeleteDraftNoteSchema.parse(args);
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(options.project_id)}/merge_requests/${options.merge_request_iid}/draft_notes/${options.draft_note_id}`;
        const response = await enhancedFetch(apiUrl, {
          method: "DELETE",
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
          },
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        return { success: true, message: "Draft note deleted successfully" };
      },
    },
  ],
]);
 
/**
 * Get read-only tool names from the registry
 */
export function getMrsReadOnlyToolNames(): string[] {
  return [
    "get_branch_diffs",
    "get_merge_request",
    "get_merge_request_diffs",
    "list_merge_request_diffs",
    "mr_discussions",
    "get_draft_note",
    "list_draft_notes",
    "list_merge_requests",
  ];
}
 
/**
 * Get all tool definitions from the registry (for backward compatibility)
 */
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();
}