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 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 | 4x 4x 4x 4x 4x 4x 4x 4x 4x 23x 20x 20x 9x 9x 9x 8x 8x 8x 1x 1x 1x 8x 8x 9x 1x 9x 9x 9x 9x 9x 9x 9x 9x 8x 2x 6x 6x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 7x 7x 8x 8x 1x 7x 6x 3x 3x 3x 3x 3x 3x 3x 1x 2x 2x 15x 12x 12x 5x 5x 5x 5x 5x 1x 5x 1x 5x 1x 5x 5x 5x 5x 5x 1x 4x 4x 3x 3x 3x 3x 1x 2x 2x 4x 4x 4x 4x 15x 12x 12x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 3x 4x 4x 4x 4x 4x 4x 1x 3x 4x 4x 4x 4x 4x 4x 4x 4x 1x 3x 9x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 4x 4x 4x 4x 1x 3x 4x 4x 4x 4x 4x 1x 3x 13x 11x 11x 6x 6x 6x 2x 2x 2x 1x 1x 1x 5x 5x 5x 5x 5x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 4x 4x 4x 1x 4x 4x 1x 4x 1x 4x 1x 4x 4x 4x 1x 3x 3x 5x 5x 5x 5x 5x 5x 5x 5x 5x 2x 3x 4x 4x 4x 4x 4x 4x 4x 4x 10x 7x 4x 4x 4x 1x 3x 3x 5x 4x 4x 4x 9x 5x 4x 4x 4x 1x 3x 3x 5x 4x 4x 4x 11x 7x 4x 4x 4x 1x 3x 5x 4x 4x 4x 4x 1x 3x 3x 6x 5x 5x 5x 5x 5x 5x 3x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 3x 1x 3x 3x 3x 3x 1x 2x 7x 7x 7x 14x 14x 7x 7x 7x 1x 6x 6x 9x 7x 7x 2x 2x 2x 1x 1x 1x 3x 3x 3x 1x 2x 2x 2x 2x 1x 1x 1x 4x 16x 4x 6x 4x 7x 6x 78x 1x | /* eslint-disable @typescript-eslint/no-unsafe-assignment */
import * as z from "zod";
import {
// Consolidated schemas
BrowseProjectsSchema,
BrowseNamespacesSchema,
BrowseCommitsSchema,
BrowseEventsSchema,
// Kept as-is schemas
GetUsersSchema,
ListProjectMembersSchema,
ListGroupIterationsSchema,
DownloadAttachmentSchema,
ListTodosSchema,
} from "./schema-readonly";
import {
// Consolidated schemas
ManageRepositorySchema,
// Kept as-is schemas
CreateBranchSchema,
CreateGroupSchema,
ManageTodosSchema,
} from "./schema";
import { enhancedFetch } from "../../utils/fetch";
import { normalizeProjectId } from "../../utils/projectIdentifier";
import { smartUserSearch, type UserSearchParams } from "../../utils/smart-user-search";
import { cleanGidsFromObject } from "../../utils/idConversion";
import { ToolRegistry, EnhancedToolDefinition } from "../../types";
import { isActionDenied } from "../../config";
/**
* Core tools registry - CQRS consolidated (Issue #16)
* Reduced from 18 tools to 10 tools + 2 todos tools = 12 total
*
* All consolidated tools use discriminated union schema pattern.
* TypeScript automatically narrows types in each switch case.
*/
export const coreToolRegistry: ToolRegistry = new Map<string, EnhancedToolDefinition>([
// ============================================================================
// CONSOLIDATED TOOLS (5 tools replacing 13 old tools)
// Uses discriminated union schema pattern - TypeScript narrows types in switch
// ============================================================================
// browse_projects: Consolidates search_repositories, list_projects, get_project
[
"browse_projects",
{
name: "browse_projects",
description:
"PROJECT DISCOVERY: Find, browse, or inspect GitLab projects. Use 'search' to find projects by name/topic across all GitLab. Use 'list' to browse your accessible projects or projects within a specific group. Use 'get' with project_id to retrieve full details of a known project. Filter by visibility, language, or ownership.",
inputSchema: z.toJSONSchema(BrowseProjectsSchema),
handler: async (args: unknown): Promise<unknown> => {
const input = BrowseProjectsSchema.parse(args);
// Runtime validation: reject denied actions even if they bypass schema filtering
Iif (isActionDenied("browse_projects", input.action)) {
throw new Error(`Action '${input.action}' is not allowed for browse_projects tool`);
}
switch (input.action) {
case "search": {
// TypeScript knows: input has q, visibility, archived, order_by, sort, with_programming_language, per_page, page (optional)
const { q, with_programming_language, visibility, order_by, sort, per_page, page } =
input;
const queryParams = new URLSearchParams();
// Handle search query
if (q) {
let finalSearchTerms = q;
// Parse topic: operator
const topicMatches = q.match(/topic:(\w+)/g);
if (topicMatches) {
const topics = topicMatches.map(match => match.replace("topic:", ""));
queryParams.set("topic", topics.join(","));
finalSearchTerms = finalSearchTerms.replace(/topic:\w+/g, "").trim();
}
Eif (finalSearchTerms) {
// Let URLSearchParams handle encoding (spaces become '+' per x-www-form-urlencoded)
// GitLab API accepts both '+' and '%20' for spaces in search queries
queryParams.set("search", finalSearchTerms);
}
}
// Add options
if (with_programming_language)
queryParams.set("with_programming_language", with_programming_language);
Iif (visibility) queryParams.set("visibility", visibility);
if (order_by) queryParams.set("order_by", order_by);
if (sort) queryParams.set("sort", sort);
if (per_page) queryParams.set("per_page", String(per_page));
Iif (page) queryParams.set("page", String(page));
queryParams.set("active", "true");
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects?${queryParams}`;
const response = await enhancedFetch(apiUrl);
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
const projects = await response.json();
return cleanGidsFromObject(projects);
}
case "list": {
// TypeScript knows: input has group_id, search, owned, starred, membership, simple, include_subgroups, with_shared, visibility, archived, order_by, sort, with_programming_language, per_page, page (optional)
const {
group_id,
search,
owned,
starred,
membership,
simple,
with_programming_language,
include_subgroups,
with_shared,
visibility,
archived,
order_by,
sort,
per_page,
page,
} = input;
const queryParams = new URLSearchParams();
// Build query parameters
if (visibility) queryParams.set("visibility", visibility);
Iif (archived !== undefined) queryParams.set("archived", String(archived));
Iif (owned !== undefined) queryParams.set("owned", String(owned));
Iif (starred !== undefined) queryParams.set("starred", String(starred));
Iif (membership !== undefined) queryParams.set("membership", String(membership));
Iif (search) queryParams.set("search", search);
Eif (simple !== undefined) queryParams.set("simple", String(simple));
Iif (order_by) queryParams.set("order_by", order_by);
Iif (sort) queryParams.set("sort", sort);
if (per_page) queryParams.set("per_page", String(per_page));
Iif (page) queryParams.set("page", String(page));
Iif (include_subgroups !== undefined)
queryParams.set("include_subgroups", String(include_subgroups));
Iif (with_shared !== undefined) queryParams.set("with_shared", String(with_shared));
Iif (with_programming_language)
queryParams.set("with_programming_language", with_programming_language);
// Set defaults
Eif (!queryParams.has("order_by")) queryParams.set("order_by", "created_at");
Eif (!queryParams.has("sort")) queryParams.set("sort", "desc");
Iif (!queryParams.has("simple")) queryParams.set("simple", "true");
if (!queryParams.has("per_page")) queryParams.set("per_page", "20");
let apiUrl: string;
if (group_id) {
apiUrl = `${process.env.GITLAB_API_URL}/api/v4/groups/${encodeURIComponent(group_id)}/projects?${queryParams}`;
} else {
queryParams.set("active", "true");
apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects?${queryParams}`;
}
const response = await enhancedFetch(apiUrl);
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
const projects = await response.json();
return cleanGidsFromObject(projects);
}
case "get": {
// TypeScript knows: input has project_id (required), statistics, license (optional)
const { project_id, statistics, license } = input;
const queryParams = new URLSearchParams();
Iif (statistics) queryParams.set("statistics", "true");
Iif (license) queryParams.set("license", "true");
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${normalizeProjectId(project_id)}?${queryParams}`;
const response = await enhancedFetch(apiUrl);
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
const project = await response.json();
return cleanGidsFromObject(project);
}
/* istanbul ignore next -- unreachable with Zod discriminatedUnion */
default:
throw new Error(`Unknown action: ${(input as { action: string }).action}`);
}
},
},
],
// browse_namespaces: Consolidates list_namespaces, get_namespace, verify_namespace
[
"browse_namespaces",
{
name: "browse_namespaces",
description:
"NAMESPACE OPERATIONS: Explore GitLab groups and user namespaces. Use 'list' to discover available namespaces for project creation. Use 'get' with namespace_id to retrieve full details including storage stats. Use 'verify' to check if a namespace path exists before creating projects or groups.",
inputSchema: z.toJSONSchema(BrowseNamespacesSchema),
handler: async (args: unknown): Promise<unknown> => {
const input = BrowseNamespacesSchema.parse(args);
// Runtime validation: reject denied actions even if they bypass schema filtering
Iif (isActionDenied("browse_namespaces", input.action)) {
throw new Error(`Action '${input.action}' is not allowed for browse_namespaces tool`);
}
switch (input.action) {
case "list": {
// TypeScript knows: input has search, owned_only, top_level_only, with_statistics, min_access_level, per_page, page (optional)
const {
search,
owned_only,
top_level_only,
with_statistics,
min_access_level,
per_page,
page,
} = input;
const queryParams = new URLSearchParams();
if (search) queryParams.set("search", search);
if (owned_only !== undefined) queryParams.set("owned_only", String(owned_only));
if (top_level_only !== undefined)
queryParams.set("top_level_only", String(top_level_only));
if (with_statistics !== undefined)
queryParams.set("with_statistics", String(with_statistics));
if (min_access_level !== undefined)
queryParams.set("min_access_level", String(min_access_level));
if (per_page) queryParams.set("per_page", String(per_page));
if (page) queryParams.set("page", String(page));
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/namespaces?${queryParams}`;
const response = await enhancedFetch(apiUrl);
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
const namespaces = await response.json();
return cleanGidsFromObject(namespaces);
}
case "get": {
// TypeScript knows: input has namespace_id (required)
const { namespace_id } = input;
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/namespaces/${encodeURIComponent(namespace_id)}`;
const response = await enhancedFetch(apiUrl);
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
const namespace = await response.json();
return cleanGidsFromObject(namespace);
}
case "verify": {
// TypeScript knows: input has namespace_id (required)
const { namespace_id } = input;
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/namespaces/${encodeURIComponent(namespace_id)}`;
const response = await enhancedFetch(apiUrl);
return {
exists: response.ok,
status: response.status,
namespace: namespace_id,
data: response.ok ? await response.json() : null,
};
}
/* istanbul ignore next -- unreachable with Zod discriminatedUnion */
default:
throw new Error(`Unknown action: ${(input as { action: string }).action}`);
}
},
},
],
// browse_commits: Consolidates list_commits, get_commit, get_commit_diff
[
"browse_commits",
{
name: "browse_commits",
description:
"COMMIT HISTORY: Explore repository commit history. Use 'list' to browse commits with optional date range, author, or file path filters. Use 'get' with sha to retrieve commit metadata and stats. Use 'diff' to see actual code changes in a commit. Essential for code review and change tracking.",
inputSchema: z.toJSONSchema(BrowseCommitsSchema),
handler: async (args: unknown): Promise<unknown> => {
const input = BrowseCommitsSchema.parse(args);
// Runtime validation: reject denied actions even if they bypass schema filtering
Iif (isActionDenied("browse_commits", input.action)) {
throw new Error(`Action '${input.action}' is not allowed for browse_commits tool`);
}
switch (input.action) {
case "list": {
// TypeScript knows: input has project_id (required), ref_name, since, until, path, author, all, with_stats, first_parent, order, trailers, per_page, page (optional)
const {
project_id,
ref_name,
since,
until,
path,
author,
all,
with_stats,
first_parent,
order,
trailers,
per_page,
page,
} = input;
const queryParams = new URLSearchParams();
if (ref_name) queryParams.set("ref_name", ref_name);
if (since) queryParams.set("since", since);
if (until) queryParams.set("until", until);
if (path) queryParams.set("path", path);
if (author) queryParams.set("author", author);
if (all !== undefined) queryParams.set("all", String(all));
if (with_stats !== undefined) queryParams.set("with_stats", String(with_stats));
if (first_parent !== undefined) queryParams.set("first_parent", String(first_parent));
if (order) queryParams.set("order", order);
if (trailers !== undefined) queryParams.set("trailers", String(trailers));
if (per_page) queryParams.set("per_page", String(per_page));
if (page) queryParams.set("page", String(page));
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(project_id)}/repository/commits?${queryParams}`;
const response = await enhancedFetch(apiUrl);
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
return await response.json();
}
case "get": {
// TypeScript knows: input has project_id (required), sha (required), stats (optional)
const { project_id, sha, stats } = input;
const queryParams = new URLSearchParams();
if (stats) queryParams.set("stats", "true");
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(project_id)}/repository/commits/${encodeURIComponent(sha)}?${queryParams}`;
const response = await enhancedFetch(apiUrl);
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
return await response.json();
}
case "diff": {
// TypeScript knows: input has project_id (required), sha (required), unidiff, per_page, page (optional)
const { project_id, sha, unidiff, per_page, page } = input;
const queryParams = new URLSearchParams();
if (unidiff) queryParams.set("unidiff", "true");
Iif (per_page) queryParams.set("per_page", String(per_page));
Iif (page) queryParams.set("page", String(page));
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(project_id)}/repository/commits/${encodeURIComponent(sha)}/diff?${queryParams}`;
const response = await enhancedFetch(apiUrl);
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
return await response.json();
}
/* istanbul ignore next -- unreachable with Zod discriminatedUnion */
default:
throw new Error(`Unknown action: ${(input as { action: string }).action}`);
}
},
},
],
// browse_events: Consolidates list_events, get_project_events
[
"browse_events",
{
name: "browse_events",
description:
"ACTIVITY FEED: Track GitLab activity and events. Use 'user' to see YOUR recent activity across all projects (commits, issues, MRs). Use 'project' with project_id to monitor a specific project's activity feed. Filter by date range or action type (pushed, commented, merged, etc.).",
inputSchema: z.toJSONSchema(BrowseEventsSchema),
handler: async (args: unknown): Promise<unknown> => {
const input = BrowseEventsSchema.parse(args);
// Runtime validation: reject denied actions even if they bypass schema filtering
Iif (isActionDenied("browse_events", input.action)) {
throw new Error(`Action '${input.action}' is not allowed for browse_events tool`);
}
// Build common query params based on action type
const buildQueryParams = (opts: {
target_type?: string;
event_action?: string;
before?: string;
after?: string;
sort?: string;
per_page?: number;
page?: number;
}) => {
const queryParams = new URLSearchParams();
if (opts.target_type) queryParams.set("target_type", opts.target_type);
if (opts.event_action) queryParams.set("action", opts.event_action);
if (opts.before) queryParams.set("before", opts.before);
if (opts.after) queryParams.set("after", opts.after);
if (opts.sort) queryParams.set("sort", opts.sort);
if (opts.per_page) queryParams.set("per_page", String(opts.per_page));
if (opts.page) queryParams.set("page", String(opts.page));
return queryParams;
};
switch (input.action) {
case "user": {
// TypeScript knows: input has target_type, event_action, before, after, sort, per_page, page (optional)
const queryParams = buildQueryParams(input);
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/events?${queryParams}`;
const response = await enhancedFetch(apiUrl);
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
return await response.json();
}
case "project": {
// TypeScript knows: input has project_id (required), target_type, event_action, before, after, sort, per_page, page (optional)
const { project_id } = input;
const queryParams = buildQueryParams(input);
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(project_id)}/events?${queryParams}`;
const response = await enhancedFetch(apiUrl);
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
return await response.json();
}
/* istanbul ignore next -- unreachable with Zod discriminatedUnion */
default:
throw new Error(`Unknown action: ${(input as { action: string }).action}`);
}
},
},
],
// manage_repository: Consolidates create_repository, fork_repository
[
"manage_repository",
{
name: "manage_repository",
description:
"REPOSITORY MANAGEMENT: Create or fork GitLab projects. Use 'create' to start a new project with custom settings (visibility, features, namespace). Use 'fork' with project_id to create your own copy of an existing project for independent development or contribution back via MRs.",
inputSchema: z.toJSONSchema(ManageRepositorySchema),
handler: async (args: unknown): Promise<unknown> => {
const input = ManageRepositorySchema.parse(args);
// Runtime validation: reject denied actions even if they bypass schema filtering
Iif (isActionDenied("manage_repository", input.action)) {
throw new Error(`Action '${input.action}' is not allowed for manage_repository tool`);
}
switch (input.action) {
case "create": {
// TypeScript knows: input has name (required), namespace, description, visibility, initialize_with_readme, issues_enabled, merge_requests_enabled, jobs_enabled, wiki_enabled, snippets_enabled, lfs_enabled, request_access_enabled, only_allow_merge_if_pipeline_succeeds, only_allow_merge_if_all_discussions_are_resolved (optional)
const {
name,
namespace,
description,
visibility,
initialize_with_readme,
issues_enabled,
merge_requests_enabled,
jobs_enabled,
wiki_enabled,
snippets_enabled,
lfs_enabled,
request_access_enabled,
only_allow_merge_if_pipeline_succeeds,
only_allow_merge_if_all_discussions_are_resolved,
} = input;
// Resolve namespace path to ID if provided
let namespaceId: string | undefined;
let resolvedNamespace: { id: string; full_path: string } | null = null;
if (namespace) {
const namespaceApiUrl = `${process.env.GITLAB_API_URL}/api/v4/namespaces/${encodeURIComponent(namespace)}`;
const namespaceResponse = await enhancedFetch(namespaceApiUrl);
if (namespaceResponse.ok) {
resolvedNamespace = (await namespaceResponse.json()) as {
id: string;
full_path: string;
};
namespaceId = String(resolvedNamespace.id);
} else {
throw new Error(`Namespace '${namespace}' not found or not accessible`);
}
}
// Check if project already exists
const targetNamespacePath = resolvedNamespace
? resolvedNamespace.full_path
: "current-user";
const projectPath = `${targetNamespacePath}/${name}`;
const checkProjectUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(projectPath)}`;
const checkResponse = await enhancedFetch(checkProjectUrl);
if (checkResponse.ok) {
const existingProject = (await checkResponse.json()) as { id: string };
throw new Error(
`Project '${projectPath}' already exists (ID: ${existingProject.id}).`
);
}
// Create project
const body = new URLSearchParams();
body.set("name", name);
// Generate path from name
const generatedPath = name
.toLowerCase()
.replace(/[^a-z0-9-]/g, "-")
.replace(/-+/g, "-")
.replace(/^-|-$/g, "");
body.set("path", generatedPath);
Iif (namespaceId) body.set("namespace_id", namespaceId);
if (description) body.set("description", description);
if (visibility) body.set("visibility", visibility);
if (initialize_with_readme) body.set("initialize_with_readme", "true");
// Add optional feature flags
if (issues_enabled !== undefined) body.set("issues_enabled", String(issues_enabled));
if (merge_requests_enabled !== undefined)
body.set("merge_requests_enabled", String(merge_requests_enabled));
if (jobs_enabled !== undefined) body.set("jobs_enabled", String(jobs_enabled));
if (wiki_enabled !== undefined) body.set("wiki_enabled", String(wiki_enabled));
if (snippets_enabled !== undefined)
body.set("snippets_enabled", String(snippets_enabled));
if (lfs_enabled !== undefined) body.set("lfs_enabled", String(lfs_enabled));
if (request_access_enabled !== undefined)
body.set("request_access_enabled", String(request_access_enabled));
if (only_allow_merge_if_pipeline_succeeds !== undefined)
body.set(
"only_allow_merge_if_pipeline_succeeds",
String(only_allow_merge_if_pipeline_succeeds)
);
if (only_allow_merge_if_all_discussions_are_resolved !== undefined)
body.set(
"only_allow_merge_if_all_discussions_are_resolved",
String(only_allow_merge_if_all_discussions_are_resolved)
);
const createApiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects`;
const createResponse = await enhancedFetch(createApiUrl, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: body.toString(),
});
if (!createResponse.ok) {
throw new Error(
`GitLab API error: ${createResponse.status} ${createResponse.statusText}`
);
}
const project = await createResponse.json();
return {
...project,
validation: {
namespace_resolved: namespace ? `${namespace} -> ${namespaceId}` : "current-user",
generated_path: generatedPath,
},
};
}
case "fork": {
// TypeScript knows: input has project_id (required), namespace, namespace_path, fork_name, fork_path, issues_enabled, merge_requests_enabled, jobs_enabled, wiki_enabled, snippets_enabled, lfs_enabled, request_access_enabled, only_allow_merge_if_pipeline_succeeds, only_allow_merge_if_all_discussions_are_resolved (optional)
const { project_id, namespace, namespace_path, fork_name, fork_path } = input;
const body = new URLSearchParams();
if (namespace) body.set("namespace", namespace);
if (namespace_path) body.set("namespace_path", namespace_path);
if (fork_name) body.set("name", fork_name);
if (fork_path) body.set("path", fork_path);
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(project_id)}/fork`;
const response = await enhancedFetch(apiUrl, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: body.toString(),
});
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
return await response.json();
}
/* istanbul ignore next -- unreachable with Zod discriminatedUnion */
default:
throw new Error(`Unknown action: ${(input as { action: string }).action}`);
}
},
},
],
// ============================================================================
// KEPT AS-IS TOOLS (5 tools - no consolidation needed)
// ============================================================================
[
"get_users",
{
name: "get_users",
description:
"FIND USERS: Search GitLab users with smart pattern detection. Auto-detects emails, usernames, or names. Supports transliteration and multi-phase fallback search.",
inputSchema: z.toJSONSchema(GetUsersSchema),
handler: async (args: unknown): Promise<unknown> => {
const options = GetUsersSchema.parse(args);
const { smart_search, search, username, public_email, ...otherParams } = options;
const hasUsernameOrEmail = Boolean(username) || Boolean(public_email);
const hasOnlySearch = Boolean(search) && !hasUsernameOrEmail;
const shouldUseSmartSearch =
smart_search === false ? false : smart_search === true || hasOnlySearch;
Iif (shouldUseSmartSearch && (search || username || public_email)) {
const query = search ?? username ?? public_email ?? "";
const additionalParams: UserSearchParams = {};
Object.entries(otherParams).forEach(([key, value]) => {
if (value !== undefined && key !== "smart_search") {
additionalParams[key] = value;
}
});
return await smartUserSearch(query, additionalParams);
} else {
const queryParams = new URLSearchParams();
Object.entries(options).forEach(([key, value]) => {
if (value !== undefined && key !== "smart_search") {
queryParams.set(key, String(value));
}
});
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/users?${queryParams}`;
const response = await enhancedFetch(apiUrl);
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
const users = await response.json();
return cleanGidsFromObject(users);
}
},
},
],
[
"list_project_members",
{
name: "list_project_members",
description:
"TEAM MEMBERS: List project members with access levels. Shows: 10=Guest, 20=Reporter, 30=Developer, 40=Maintainer, 50=Owner.",
inputSchema: z.toJSONSchema(ListProjectMembersSchema),
handler: async (args: unknown): Promise<unknown> => {
const options = ListProjectMembersSchema.parse(args);
const { project_id } = options;
const queryParams = new URLSearchParams();
Object.entries(options).forEach(([key, value]) => {
if (value !== undefined && key !== "project_id") {
queryParams.set(key, String(value));
}
});
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(project_id)}/members?${queryParams}`;
const response = await enhancedFetch(apiUrl);
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
const members = await response.json();
return cleanGidsFromObject(members);
},
},
],
[
"list_group_iterations",
{
name: "list_group_iterations",
description:
"SPRINTS: List iterations/sprints for agile planning. Filter by state: current, upcoming, closed. Requires GitLab Premium.",
inputSchema: z.toJSONSchema(ListGroupIterationsSchema),
handler: async (args: unknown): Promise<unknown> => {
const options = ListGroupIterationsSchema.parse(args);
const { group_id } = options;
const queryParams = new URLSearchParams();
Object.entries(options).forEach(([key, value]) => {
if (value !== undefined && key !== "group_id") {
queryParams.set(key, String(value));
}
});
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/groups/${encodeURIComponent(group_id)}/iterations?${queryParams}`;
const response = await enhancedFetch(apiUrl);
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
return await response.json();
},
},
],
[
"download_attachment",
{
name: "download_attachment",
description:
"DOWNLOAD: Retrieve file attachments from issues/MRs. Requires secret token and filename from attachment URL.",
inputSchema: z.toJSONSchema(DownloadAttachmentSchema),
handler: async (args: unknown): Promise<unknown> => {
const options = DownloadAttachmentSchema.parse(args);
const { project_id, secret, filename } = options;
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(project_id)}/uploads/${secret}/${filename}`;
const response = await enhancedFetch(apiUrl);
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
const attachment = await response.arrayBuffer();
return {
filename,
content: Buffer.from(attachment).toString("base64"),
contentType: response.headers.get("content-type") ?? "application/octet-stream",
};
},
},
],
[
"create_branch",
{
name: "create_branch",
description:
"NEW BRANCH: Create a Git branch from existing ref. Required before creating MRs. Ref can be branch name, tag, or commit SHA.",
inputSchema: z.toJSONSchema(CreateBranchSchema),
handler: async (args: unknown): Promise<unknown> => {
const options = CreateBranchSchema.parse(args);
const body = new URLSearchParams();
body.set("branch", options.branch);
body.set("ref", options.ref);
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${encodeURIComponent(options.project_id)}/repository/branches`;
const response = await enhancedFetch(apiUrl, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: body.toString(),
});
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
return await response.json();
},
},
],
[
"create_group",
{
name: "create_group",
description:
"CREATE GROUP: Create a new GitLab group/namespace. Groups organize projects and teams. Can create subgroups with parent_id.",
inputSchema: z.toJSONSchema(CreateGroupSchema),
handler: async (args: unknown): Promise<unknown> => {
const options = CreateGroupSchema.parse(args);
const body = new URLSearchParams();
body.set("name", options.name);
body.set("path", options.path);
if (options.description) body.set("description", options.description);
Eif (options.visibility) body.set("visibility", options.visibility);
if (options.parent_id !== undefined) body.set("parent_id", String(options.parent_id));
if (options.lfs_enabled !== undefined) body.set("lfs_enabled", String(options.lfs_enabled));
if (options.request_access_enabled !== undefined)
body.set("request_access_enabled", String(options.request_access_enabled));
if (options.default_branch_protection !== undefined)
body.set("default_branch_protection", String(options.default_branch_protection));
if (options.avatar) body.set("avatar", options.avatar);
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/groups`;
const response = await enhancedFetch(apiUrl, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: body.toString(),
});
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
return await response.json();
},
},
],
// ============================================================================
// TODOS TOOLS (discriminated union schema)
// TypeScript automatically narrows types in each switch case
// ============================================================================
[
"list_todos",
{
name: "list_todos",
description:
"TASK QUEUE: View your GitLab todos (notifications requiring action). Todos are auto-created when you're assigned to issues/MRs, @mentioned, requested as reviewer, or CI pipelines fail. Filter by state (pending/done), action type (assigned, mentioned, review_requested), or target type (Issue, MergeRequest).",
inputSchema: z.toJSONSchema(ListTodosSchema),
handler: async (args: unknown): Promise<unknown> => {
const options = ListTodosSchema.parse(args);
const queryParams = new URLSearchParams();
Object.entries(options).forEach(([key, value]) => {
Eif (value !== undefined) {
queryParams.set(key, String(value));
}
});
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/todos?${queryParams}`;
const response = await enhancedFetch(apiUrl);
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
const todos = await response.json();
return cleanGidsFromObject(todos);
},
},
],
[
"manage_todos",
{
name: "manage_todos",
description:
"TODO ACTIONS: Manage your GitLab todo items. Use 'mark_done' with id to complete a single todo (returns the updated todo object). Use 'mark_all_done' to clear your entire todo queue (returns success status). Use 'restore' with id to undo a completed todo (returns the restored todo object).",
inputSchema: z.toJSONSchema(ManageTodosSchema),
handler: async (args: unknown): Promise<unknown> => {
const input = ManageTodosSchema.parse(args);
// Runtime validation: reject denied actions even if they bypass schema filtering
Iif (isActionDenied("manage_todos", input.action)) {
throw new Error(`Action '${input.action}' is not allowed for manage_todos tool`);
}
switch (input.action) {
case "mark_done": {
// TypeScript knows: input has id (required)
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/todos/${input.id}/mark_as_done`;
const response = await enhancedFetch(apiUrl, { method: "POST" });
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
const todo = await response.json();
return cleanGidsFromObject(todo);
}
case "mark_all_done": {
// TypeScript knows: no additional fields needed
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/todos/mark_all_as_done`;
const response = await enhancedFetch(apiUrl, { method: "POST" });
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
return { success: true, message: "All todos marked as done" };
}
case "restore": {
// TypeScript knows: input has id (required)
const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/todos/${input.id}/mark_as_pending`;
const response = await enhancedFetch(apiUrl, { method: "POST" });
if (!response.ok) {
throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
}
const todo = await response.json();
return cleanGidsFromObject(todo);
}
/* 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 getCoreReadOnlyToolNames(): string[] {
return [
// Consolidated read tools
"browse_projects",
"browse_namespaces",
"browse_commits",
"browse_events",
// Kept as-is read tools
"get_users",
"list_project_members",
"list_group_iterations",
"download_attachment",
"list_todos",
];
}
/**
* Get all tool definitions from the registry
*/
export function getCoreToolDefinitions(): EnhancedToolDefinition[] {
return Array.from(coreToolRegistry.values());
}
/**
* Get filtered tools based on read-only mode
*/
export function getFilteredCoreTools(readOnlyMode: boolean = false): EnhancedToolDefinition[] {
if (readOnlyMode) {
const readOnlyNames = getCoreReadOnlyToolNames();
return Array.from(coreToolRegistry.values()).filter(tool => readOnlyNames.includes(tool.name));
}
return getCoreToolDefinitions();
}
|