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 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 | 1x 1x 1x 1x 1x 82x 82x 82x 102x 102x 9x 9x 1x 1x 11x 11x 3x 1x 1x 1x 3x 3x 10x 1x 1x 1x 10x 10x 2x 2x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 8x 8x 3x 3x 14x 1x 1x 1x 14x 14x 14x 1x 1x 1x 14x 14x 9x 9x 6x 1x 1x 1x 6x 6x 2x 2x 2x 1x 1x 1x 1x 1x 82x 2x 71x 2x 2x 2x 1x 1x 69x 65x 1x 1x 64x 4x 1x 3x 4x 2x 1x 14x 14x 8x 9x 9x 9x 9x 9x 9x 9x 9x 14x 14x 2x 2x 2x 2x 2x 2x 36x 36x 3x 3x 1x 28x 28x 28x 364x 1092x 28x 30x 30x 28x 30x 28x 28x 28x 392x 28x 28x 1x 21x 21x 15x 26x 26x 26x 26x 26x 15x 6x 6x 2x 4x 4x 4x 6x 3x 3x 3x 3x 21x 3x 11x 106x 105x 98x 98x 97x 11x 11x 3x 3x 8x 8x 8x 14x 14x 14x 14x 49x 35x 35x 35x 35x 34x 35x 35x 35x 1x 8x 34x 22x 21x 13x 13x 12x 13x 8x 8x 12x 1x 8x 10x 10x 10x 8x 10x 10x 10x 7x 7x 3x 3x 10x 10x 55x 45x 45x 45x 21x 1x 20x 2x 18x 1x 17x 1x 16x 1x 15x 1x 14x 1x 13x 1x 12x 1x 11x 1x 10x 1x 9x 1x 8x 2x 6x 1x 5x 1x 4x 1x 3x 10x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 9x 9x 9x 9x 9x 16x 9x 11x 11x 11x 11x 11x 11x 6x 1x 1x 6x 6x 6x 42x 42x 42x 6x 11x 6x 6x 12x 12x 12x 12x 12x 12x 12x 13x 13x 13x 12x 11x 10x 10x 8x 8x 8x 8x 8x 8x 11x 11x 11x 3x 3x 9x 7x 7x 3x 4x 3x 9x 3x 2x 2x 2x 2x 1x 1x 1x 1x 1x 2x 3x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 2x 2x 2x 1x 10x 1x 3x 10x 1x 11x 11x 1x 3x 10x 11x 11x 11x 4x 1x 4x 11x 2x 2x 6x 1x 6x 1x 11x 11x 4x 44x 44x 3x 12x 3x 12x 11x 8x 11x 11x 8x 1x 2x 2x 1x 1x 7x 7x 7x 7x 7x 7x 8x 8x 8x 8x 8x 7x 1x 1x 7x 3x 3x 3x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 2x 2x 2x 7x 7x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 11x 11x 11x 1x 6x 6x 2x 6x 6x 6x 4x 6x 6x 27x 6x 6x 1x 1x 4x 1x 6x 4x 4x 4x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 1x 1x 1x 12x 2x 2x 1x 1x 2x 2x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 10x 1x 10x 10x 2x 2x 1x 2x 1x 10x 3x 3x 1x 3x 1x 3x 1x 10x 3x 3x 3x 1x 2x 1x 1x 1x 2x 1x 1x 1x 2x 4x 4x 1x 1x 1x 3x 3x 1x 1x 1x 2x 2x 2x 2x 6x 7x 6x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 1x 10x 1x 82x 82x 1x 1x 1x 1x 81x 1x 1x 1x 1x 1x 80x 2x 80x 80x 3x 3x 3x 3x 3x 77x 77x 37x 99x 37x 8x 8x 29x 3x 3x 26x 4x 4x 22x 9x 9x 13x 13x 13x 40x 41x 39x 39x 2x 2x 2x 2x 2x 2x 2x 39x 9x 9x 1x 1x 39x 1x 1x 1x 1x 1x 1x 11x 11x 11x 26x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 17x 17x 17x 17x 17x 6x 6x 6x 2x 4x 6x 11x 8x 8x 8x 8x 8x 8x 8x 8x 7x 2x 8x 26x 39x 2x 2x 1x |
/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-non-null-assertion, no-case-declarations */
import * as fs from "fs";
import * as path from "path";
import { RegistryManager } from "../registry-manager";
import { ToolAvailability } from "../services/ToolAvailability";
import { EnhancedToolDefinition } from "../types";
import { ProfileLoader, Preset, Profile } from "../profiles";
interface JsonSchemaProperty {
type?: string;
$ref?: string;
properties?: Record<string, JsonSchemaProperty>;
items?: JsonSchemaProperty;
enum?: unknown[];
oneOf?: JsonSchemaProperty[];
anyOf?: JsonSchemaProperty[];
description?: string;
required?: string[];
_def?: {
schema?: {
_def?: {
checks?: Array<{ message?: string }>;
};
};
};
[key: string]: unknown;
}
interface CliOptions {
format: "markdown" | "json" | "simple" | "export";
entity?: string;
tool?: string;
showEnv?: boolean;
showEnvGates?: boolean;
verbose?: boolean;
detail?: boolean;
noExamples?: boolean;
toc?: boolean;
// Profile/Preset inspection flags
showPresets?: boolean;
showProfiles?: boolean;
preset?: string;
profile?: string;
validate?: boolean;
compare?: string;
}
function parseArgs(): CliOptions {
const args = process.argv.slice(2);
const options: CliOptions = {
format: "markdown",
showEnv: false,
showEnvGates: false,
verbose: false,
detail: false,
noExamples: false,
toc: false,
showPresets: false,
showProfiles: false,
validate: false,
};
for (let i = 0; i < args.length; i++) {
const arg = args[i];
switch (arg) {
case "--json":
options.format = "json";
break;
case "--simple":
options.format = "simple";
break;
case "--export":
options.format = "export";
break;
case "--entity":
if (i + 1 >= args.length) {
console.error("Error: --entity flag requires a value.");
console.error("Usage: yarn list-tools --entity <entity_name>");
process.exit(1);
}
options.entity = args[++i];
break;
case "--tool":
if (i + 1 >= args.length) {
console.error("Error: --tool flag requires a value.");
console.error("Usage: yarn list-tools --tool <tool_name>");
process.exit(1);
}
options.tool = args[++i];
break;
case "--env":
options.showEnv = true;
break;
case "--env-gates":
options.showEnvGates = true;
break;
case "--verbose":
case "-v":
options.verbose = true;
break;
case "--detail":
options.detail = true;
break;
case "--no-examples":
options.noExamples = true;
break;
case "--toc":
options.toc = true;
break;
case "--presets":
options.showPresets = true;
break;
case "--profiles":
options.showProfiles = true;
break;
case "--preset":
if (i + 1 >= args.length) {
console.error("Error: --preset flag requires a value.");
console.error("Usage: yarn list-tools --preset <preset_name>");
process.exit(1);
}
options.preset = args[++i];
break;
case "--profile":
if (i + 1 >= args.length) {
console.error("Error: --profile flag requires a value.");
console.error("Usage: yarn list-tools --profile <profile_name>");
process.exit(1);
}
options.profile = args[++i];
break;
case "--validate":
options.validate = true;
break;
case "--compare":
if (i + 1 >= args.length) {
console.error("Error: --compare flag requires a value.");
console.error("Usage: yarn list-tools --preset <name> --compare <other_name>");
process.exit(1);
}
options.compare = args[++i];
break;
case "--help":
case "-h":
printHelp();
process.exit(0);
break;
default:
Eif (arg.startsWith("-")) {
console.error(`Error: Unrecognized option '${arg}'.`);
console.error("Use '--help' to see available options.");
process.exit(1);
}
break;
}
}
return options;
}
function printHelp(): void {
console.log(`
GitLab MCP Tool Lister
Usage: yarn list-tools [options]
Tool Options:
--json Output in JSON format
--simple Simple list of tool names
--export Generate complete TOOLS.md documentation
--env-gates Show USE_* environment variable gates
--entity <name> Filter by entity (e.g., workitems, labels, mrs)
--tool <name> Show details for specific tool
--env Show environment configuration
--verbose, -v Show additional details
--detail Show all tools with their input schemas
--no-examples Skip example JSON blocks (for --export)
--toc Include table of contents (for --export)
Profile/Preset Options:
--presets List all available presets (built-in and user)
--profiles List user-defined profiles
--preset <name> Inspect a specific preset
--profile <name> Inspect a specific profile
--validate Validate configuration (use with --preset or --profile)
--compare <name> Compare two presets (use with --preset)
General:
--help, -h Show this help
Examples:
yarn list-tools # List all tools in markdown
yarn list-tools --json # JSON output
yarn list-tools --export # Generate TOOLS.md to stdout
yarn list-tools --export > docs/TOOLS.md # Generate TOOLS.md to file
yarn list-tools --export --toc # With table of contents
yarn list-tools --export --no-examples # Skip example JSON blocks
yarn list-tools --env-gates # Show USE_* variable gates
yarn list-tools --env-gates --json # JSON output of gates
yarn list-tools --entity workitems # Only work items tools
yarn list-tools --tool list_work_items # Specific tool details
Profile/Preset Examples:
yarn list-tools --presets # List all presets
yarn list-tools --profiles # List user profiles
yarn list-tools --preset junior-dev # Inspect preset details
yarn list-tools --preset junior-dev --validate # Validate preset
yarn list-tools --preset junior-dev --compare senior-dev # Compare presets
yarn list-tools --presets --json # JSON output of presets
Environment Variables:
GITLAB_READONLY Show only read-only tools
GITLAB_DENIED_TOOLS_REGEX Regex pattern to exclude tools
GITLAB_ALLOWED_TOOLS_REGEX Regex pattern to include tools
`);
}
function resolveJsonSchemaType(prop: JsonSchemaProperty, schema: JsonSchemaProperty): string {
// Handle $ref references
if (prop.$ref) {
const refPath = prop.$ref.replace("#/properties/", "");
const referencedProp = schema.properties?.[refPath];
if (referencedProp) {
return resolveJsonSchemaType(referencedProp, schema);
}
return "reference";
}
// Handle direct type
if (prop.type) {
if (prop.type === "array" && prop.items) {
const itemType = resolveJsonSchemaType(prop.items, schema);
return `${itemType}[]`;
}
return prop.type;
}
// Handle enum without explicit type (usually string)
if (prop.enum) {
return "enum";
}
// Handle union types
if (prop.oneOf ?? prop.anyOf) {
const unionTypes =
(prop.oneOf ?? prop.anyOf)?.map(option => resolveJsonSchemaType(option, schema)) ?? [];
return unionTypes.join(" | ");
}
return "unknown";
}
function getParameterDescription(schema: JsonSchemaProperty): string[] {
const params: string[] = [];
if (schema.properties) {
for (const [key, value] of Object.entries(schema.properties)) {
const prop = value;
const required = schema.required?.includes(key) ?? false;
const type = resolveJsonSchemaType(prop, schema);
const description = prop.description ?? "";
let paramStr = ` - \`${key}\` (${type}${required ? ", required" : ", optional"})`;
Eif (description) {
paramStr += `: ${description}`;
}
params.push(paramStr);
}
}
// Handle refinements (like list_work_items with exactly one of groupPath/projectPath)
Iif (schema._def?.schema?._def?.checks) {
const checks = schema._def.schema._def.checks;
for (const check of checks) {
if (check.message) {
params.push(` - **Validation**: ${check.message}`);
}
}
}
return params;
}
function printEnvironmentInfo(): void {
console.log("=== Environment Configuration ===\n");
console.log(`GITLAB_READONLY: ${process.env.GITLAB_READONLY ?? "false"}`);
console.log(`GITLAB_DENIED_TOOLS_REGEX: ${process.env.GITLAB_DENIED_TOOLS_REGEX ?? "(not set)"}`);
console.log(
`GITLAB_ALLOWED_TOOLS_REGEX: ${process.env.GITLAB_ALLOWED_TOOLS_REGEX ?? "(not set)"}`
);
console.log(`GITLAB_API_URL: ${process.env.GITLAB_API_URL ?? "https://gitlab.com"}`);
console.log();
}
function getToolTierInfo(toolName: string): string {
const requirement = ToolAvailability.getToolRequirement(toolName);
if (!requirement) return "";
const tierBadge =
{
free: "Free",
premium: "Premium",
ultimate: "Ultimate",
}[requirement.requiredTier] ?? requirement.requiredTier;
return `[tier: ${tierBadge}]`;
}
/**
* Map of entity names to their CQRS tool names.
* Organization notes:
* - Core: Project/namespace/commit/event tools (consolidated from 18 to ~11 tools)
* - Todos: Separate category for list_todos and manage_todos (originally part of core registry
* but categorized separately for documentation clarity)
* - Each entity maps to browse_ and manage_ prefixed tools (or legacy list_ and get_ prefixed)
*/
const ENTITY_TOOLS: Record<string, string[]> = {
Core: [
"browse_projects",
"browse_namespaces",
"browse_commits",
"browse_events",
"create_branch",
"create_group",
"manage_repository",
"list_project_members",
"list_group_iterations",
"download_attachment",
"get_users",
],
"Work Items": ["browse_work_items", "manage_work_item"],
"Merge Requests": [
"browse_merge_requests",
"browse_mr_discussions",
"manage_merge_request",
"manage_mr_discussion",
"manage_draft_notes",
],
Labels: ["browse_labels", "manage_label"],
Wiki: ["browse_wiki", "manage_wiki"],
Pipelines: ["browse_pipelines", "manage_pipeline", "manage_pipeline_job"],
Variables: ["browse_variables", "manage_variable"],
Milestones: ["browse_milestones", "manage_milestone"],
Files: ["browse_files", "manage_files"],
Snippets: ["browse_snippets", "manage_snippet"],
Webhooks: ["list_webhooks", "manage_webhook"],
Integrations: ["list_integrations", "manage_integration"],
Todos: ["list_todos", "manage_todos"],
};
function groupToolsByEntity(tools: any[]): Map<string, any[]> {
const grouped = new Map<string, any[]>();
// Build reverse lookup: tool name -> entity
const toolToEntity = new Map<string, string>();
for (const [entity, toolNames] of Object.entries(ENTITY_TOOLS)) {
for (const toolName of toolNames) {
toolToEntity.set(toolName, entity);
}
}
for (const tool of tools) {
const entity = toolToEntity.get(tool.name) ?? "Other";
if (!grouped.has(entity)) {
grouped.set(entity, []);
}
grouped.get(entity)!.push(tool);
}
// Sort entities in a logical order
const entityOrder = [
"Core",
"Work Items",
"Merge Requests",
"Labels",
"Milestones",
"Pipelines",
"Variables",
"Files",
"Wiki",
"Snippets",
"Webhooks",
"Integrations",
"Todos",
"Other",
];
const sortedGrouped = new Map<string, any[]>();
for (const entity of entityOrder) {
if (grouped.has(entity)) {
sortedGrouped.set(entity, grouped.get(entity)!);
}
}
return sortedGrouped;
}
interface ActionInfo {
name: string;
description: string;
}
interface ParameterInfo {
name: string;
type: string;
required: boolean;
description: string;
}
interface ActionParameter extends ParameterInfo {
requiredForAction: boolean; // Required specifically for this action
}
interface GroupedParameters {
common: ParameterInfo[]; // Shared across all actions
byAction: Map<string, ActionParameter[]>; // Action-specific parameters
}
// Action descriptions for documentation generation
const ACTION_DESCRIPTIONS: Record<string, string> = {
list: "List items with filtering and pagination",
get: "Get a single item by ID",
create: "Create a new item",
update: "Update an existing item",
delete: "Delete an item",
search: "Search for items",
diffs: "Get file changes/diffs",
compare: "Compare two branches or commits",
merge: "Merge a merge request",
approve: "Approve a merge request",
unapprove: "Remove approval from a merge request",
rebase: "Rebase a merge request",
cancel: "Cancel a running operation",
retry: "Retry a failed operation",
play: "Run a manual job",
publish: "Publish draft notes",
drafts: "List draft notes",
draft: "Get a single draft note",
resolve: "Resolve a discussion thread",
unresolve: "Unresolve a discussion thread",
note: "Add a note/comment",
mark_done: "Mark as done",
mark_pending: "Mark as pending",
disable: "Disable the integration",
test: "Test a webhook",
read: "Read item details",
};
/**
* Extract actions from a CQRS schema.
* Tries oneOf branches first (discriminated union), falls back to action.enum (flat schema)
*/
function extractActions(schema: JsonSchemaProperty): ActionInfo[] {
const actions: ActionInfo[] = [];
// Try discriminated union (oneOf) first - has richer descriptions
if (schema.oneOf && Array.isArray(schema.oneOf)) {
for (const branch of schema.oneOf) {
const actionProp = branch.properties?.action;
// In discriminated union, action has "const" instead of "enum"
const actionName = actionProp?.const as string | undefined;
Eif (actionName) {
// Use description from schema, fallback to ACTION_DESCRIPTIONS
const description =
(actionProp?.description as string) ??
ACTION_DESCRIPTIONS[actionName] ??
`Perform ${actionName} operation`;
actions.push({ name: actionName, description });
}
}
return actions;
}
// Fallback: flat schema with action enum
const actionProp = schema.properties?.action;
if (actionProp?.enum && Array.isArray(actionProp.enum)) {
for (const actionName of actionProp.enum) {
Eif (typeof actionName === "string") {
const description = ACTION_DESCRIPTIONS[actionName] ?? `Perform ${actionName} operation`;
actions.push({ name: actionName, description });
}
}
}
return actions;
}
/**
* Extract parameters from flat schema.
* Only called for schemas without oneOf (flat schemas).
* For oneOf schemas, use extractParametersGrouped which handles them directly.
*/
function extractParameters(schema: JsonSchemaProperty): ParameterInfo[] {
Iif (!schema.properties) return [];
const requiredFields = schema.required ?? [];
const params: ParameterInfo[] = [];
for (const [name, prop] of Object.entries(schema.properties)) {
params.push({
name,
type: resolveJsonSchemaType(prop, schema),
required: requiredFields.includes(name),
description: prop.description ?? "",
});
}
return sortParameters(params);
}
function sortParameters(params: ParameterInfo[]): ParameterInfo[] {
return params.sort((a, b) => {
if (a.required && !b.required) return -1;
if (!a.required && b.required) return 1;
Iif (a.name === "action") return -1;
if (b.name === "action") return 1;
return a.name.localeCompare(b.name);
});
}
/**
* Extract parameters grouped by common (all actions) vs action-specific.
* Returns structured data for human-readable documentation.
*/
function extractParametersGrouped(schema: JsonSchemaProperty): GroupedParameters {
const result: GroupedParameters = {
common: [],
byAction: new Map(),
};
// Only works with discriminated unions (oneOf)
if (!schema.oneOf || !Array.isArray(schema.oneOf)) {
// Flat schema - all params are "common"
result.common = extractParameters(schema);
return result;
}
const totalActions = schema.oneOf.length;
// Track parameter occurrences across actions
const paramOccurrences = new Map<
string,
{
actions: Map<string, { required: boolean; type: string; description: string }>;
type: string;
description: string;
}
>();
// Collect all parameters from all action branches
for (const branch of schema.oneOf) {
const actionName = branch.properties?.action?.const as string | undefined;
Iif (!actionName || !branch.properties) continue;
const requiredFields = branch.required ?? [];
for (const [name, prop] of Object.entries(branch.properties)) {
if (name === "action") continue; // Skip action field itself
const type = resolveJsonSchemaType(prop, branch);
const required = requiredFields.includes(name);
const description = prop.description ?? "";
if (!paramOccurrences.has(name)) {
paramOccurrences.set(name, {
actions: new Map(),
type,
description,
});
}
const occurrence = paramOccurrences.get(name)!;
occurrence.actions.set(actionName, { required, type, description });
// Use longer description
if (description.length > occurrence.description.length) {
occurrence.description = description;
}
}
}
// Separate into common vs action-specific
for (const [name, data] of paramOccurrences) {
if (data.actions.size === totalActions) {
// Parameter appears in ALL actions - it's common
// Required only if required in all actions
const requiredInAll = Array.from(data.actions.values()).every(a => a.required);
result.common.push({
name,
type: data.type,
required: requiredInAll,
description: data.description,
});
} else {
// Parameter is action-specific
for (const [actionName, actionData] of data.actions) {
if (!result.byAction.has(actionName)) {
result.byAction.set(actionName, []);
}
result.byAction.get(actionName)!.push({
name,
type: actionData.type,
required: actionData.required,
requiredForAction: actionData.required,
description: actionData.description || data.description,
});
}
}
}
// Sort parameters
result.common = sortParameters(result.common);
for (const [action, params] of result.byAction) {
result.byAction.set(
action,
params.sort((a, b) => {
Eif (a.requiredForAction && !b.requiredForAction) return -1;
if (!a.requiredForAction && b.requiredForAction) return 1;
return a.name.localeCompare(b.name);
})
);
}
return result;
}
/**
* Generate example JSON for a tool based on its schema
*/
function generateExample(schema: JsonSchemaProperty): Record<string, unknown> {
const example: Record<string, unknown> = {};
const actions = extractActions(schema);
// Use first action as default
if (actions.length > 0) {
example.action = actions[0].name;
}
// For oneOf, use first branch for example
let targetSchema = schema;
let requiredFields: string[] = [];
if (schema.oneOf && Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
targetSchema = schema.oneOf[0];
requiredFields = targetSchema.required ?? [];
} else if (schema.properties) {
requiredFields = schema.required ?? [];
} else E{
return example;
}
Iif (!targetSchema.properties) return example;
for (const [name, prop] of Object.entries(targetSchema.properties)) {
if (name === "action") continue; // Already handled
const isRequired = requiredFields.includes(name);
const description = (prop.description ?? "").toLowerCase();
// Only include required fields and some common optional ones
if (!isRequired) continue;
// Generate example values based on type and name
if (prop.enum && Array.isArray(prop.enum) && prop.enum.length > 0) {
example[name] = prop.enum[0];
} else if (name.includes("project_id") || name === "projectId") {
example[name] = "my-group/my-project";
} else if (name.includes("group_id") || name === "groupId") {
example[name] = "my-group";
} else if (name.includes("namespace")) {
example[name] = "my-group/my-project";
} else if (name.includes("_iid") || name === "iid") {
example[name] = "1";
} else if (name.includes("_id") || name === "id") {
example[name] = "123";
} else if (name === "title") {
example[name] = "Example title";
} else if (name === "description") {
example[name] = "Example description";
} else if (name === "url") {
example[name] = "https://example.com/webhook";
} else if (name === "content") {
example[name] = "File content here";
} else if (name === "file_path" || name === "path") {
example[name] = "path/to/file.txt";
} else if (name === "ref" || name === "branch") {
example[name] = "main";
} else if (name === "from" || name === "to") {
example[name] = name === "from" ? "main" : "feature-branch";
} else if (description.includes("boolean") || prop.type === "boolean") {
example[name] = true;
} else if (prop.type === "number" || prop.type === "integer") {
example[name] = 10;
} else if (prop.type === "array") {
example[name] = [];
} else {
example[name] = `example_${name}`;
}
}
return example;
}
/**
* Get package version from package.json
* Looks for exact package name first, falls back to first package.json found
*/
function getPackageVersion(): string {
try {
// Find package.json by looking for it from cwd upwards
let dir = process.cwd();
let fallbackVersion: string | null = null;
for (let i = 0; i < 5; i++) {
const pkgPath = path.join(dir, "package.json");
Eif (fs.existsSync(pkgPath)) {
const content = fs.readFileSync(pkgPath, "utf8");
const pkg = JSON.parse(content) as { version?: string; name?: string };
// Store first found version as fallback
Eif (fallbackVersion === null && pkg.version) {
fallbackVersion = pkg.version;
}
// Verify it's our package (exact match preferred)
Eif (pkg.name === "@structured-world/gitlab-mcp") {
return pkg.version ?? "unknown";
}
}
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
// Use fallback version if exact package not found (dev/testing scenarios)
return fallbackVersion ?? "unknown";
} catch {
return "unknown";
}
}
/**
* Generate complete TOOLS.md content
*/
function generateExportMarkdown(
tools: any[],
options: { noExamples?: boolean; toc?: boolean }
): string {
const lines: string[] = [];
const version = getPackageVersion();
const timestamp = new Date().toISOString().split("T")[0];
// Header
lines.push("# GitLab MCP Tools Reference");
lines.push("");
lines.push("> Auto-generated from source code. Do not edit manually.");
lines.push(`> Generated: ${timestamp} | Tools: ${tools.length} | Version: ${version}`);
lines.push("");
const grouped = groupToolsByEntity(tools);
// Table of Contents
if (options.toc) {
lines.push("## Table of Contents");
lines.push("");
for (const [entity, entityTools] of grouped) {
const anchor = entity.toLowerCase().replace(/\s+/g, "-");
lines.push(`- [${entity} (${entityTools.length})](#${anchor})`);
}
lines.push("");
lines.push("---");
lines.push("");
}
// Tools by category
for (const [entity, entityTools] of grouped) {
lines.push(`## ${entity}`);
lines.push("");
for (const tool of entityTools) {
const tierInfo = getToolTierInfo(tool.name);
const tierDisplay = tierInfo ? ` ${tierInfo}` : "";
lines.push(`### ${tool.name}${tierDisplay}`);
lines.push("");
lines.push(tool.description);
lines.push("");
// Actions table
const actions = extractActions(tool.inputSchema);
if (actions.length > 0) {
lines.push("#### Actions");
lines.push("");
lines.push("| Action | Description |");
lines.push("|--------|-------------|");
for (const action of actions) {
lines.push(`| \`${action.name}\` | ${action.description} |`);
}
lines.push("");
}
// Parameters - grouped by common vs action-specific
const groupedParams = extractParametersGrouped(tool.inputSchema);
const hasParams = groupedParams.common.length > 0 || groupedParams.byAction.size > 0;
Eif (hasParams) {
lines.push("#### Parameters");
lines.push("");
// Common parameters (shared across all actions)
if (groupedParams.common.length > 0) {
if (groupedParams.byAction.size > 0) {
lines.push("**Common** (all actions):");
lines.push("");
}
lines.push("| Parameter | Type | Required | Description |");
lines.push("|-----------|------|----------|-------------|");
for (const param of groupedParams.common) {
const req = param.required ? "Yes" : "No";
const desc = param.description || "-";
lines.push(`| \`${param.name}\` | ${param.type} | ${req} | ${desc} |`);
}
lines.push("");
}
// Action-specific parameters
if (groupedParams.byAction.size > 0) {
const sortedActions = Array.from(groupedParams.byAction.keys()).sort();
for (const actionName of sortedActions) {
const actionParams = groupedParams.byAction.get(actionName)!;
Iif (actionParams.length === 0) continue;
lines.push(`**Action \`${actionName}\`**:`);
lines.push("");
lines.push("| Parameter | Type | Required | Description |");
lines.push("|-----------|------|----------|-------------|");
for (const param of actionParams) {
const req = param.requiredForAction ? "Yes" : "No";
const desc = param.description || "-";
lines.push(`| \`${param.name}\` | ${param.type} | ${req} | ${desc} |`);
}
lines.push("");
}
}
}
// Example
if (!options.noExamples && tool.inputSchema) {
const example = generateExample(tool.inputSchema);
if (Object.keys(example).length > 0) {
lines.push("#### Example");
lines.push("");
lines.push("```json");
lines.push(JSON.stringify(example, null, 2));
lines.push("```");
lines.push("");
}
}
lines.push("---");
lines.push("");
}
}
return lines.join("\n");
}
// ============================================================================
// Environment Gates Functions
// ============================================================================
interface EnvGateInfo {
envVar: string;
defaultValue: boolean;
tools: string[];
}
/**
* Extract environment gate information from tool definitions
*/
function extractEnvGates(tools: EnhancedToolDefinition[]): EnvGateInfo[] {
const gatesMap = new Map<string, EnvGateInfo>();
for (const tool of tools) {
if (tool.gate) {
const existing = gatesMap.get(tool.gate.envVar);
if (existing) {
existing.tools.push(tool.name);
} else {
gatesMap.set(tool.gate.envVar, {
envVar: tool.gate.envVar,
defaultValue: tool.gate.defaultValue,
tools: [tool.name],
});
}
}
}
// Sort by envVar name and return as array
return Array.from(gatesMap.values()).sort((a, b) => a.envVar.localeCompare(b.envVar));
}
/**
* Get tools without any gate (always enabled)
*/
function getUngatedTools(tools: EnhancedToolDefinition[]): string[] {
return tools.filter(tool => !tool.gate).map(tool => tool.name);
}
/**
* Print env gates in markdown table format
*/
function printEnvGatesMarkdown(
gates: EnvGateInfo[],
ungatedTools: string[],
format: "markdown" | "json"
): void {
if (format === "json") {
const output = {
gates: gates.map(g => ({
envVar: g.envVar,
defaultValue: g.defaultValue,
tools: g.tools,
})),
ungated: {
description: "Core tools (always enabled)",
tools: ungatedTools,
},
};
console.log(JSON.stringify(output, null, 2));
return;
}
// Markdown format
console.log("# Environment Variable Gates\n");
console.log("This table shows which `USE_*` environment variables control which tools.\n");
console.log("| Variable | Default | Tools Controlled |");
console.log("|----------|---------|------------------|");
for (const gate of gates) {
const defaultStr = gate.defaultValue ? "`true`" : "`false`";
const toolsStr = gate.tools.map(t => `\`${t}\``).join(", ");
console.log(`| \`${gate.envVar}\` | ${defaultStr} | ${toolsStr} |`);
}
// Show ungated (core) tools
Eif (ungatedTools.length > 0) {
const toolsStr = ungatedTools.map(t => `\`${t}\``).join(", ");
console.log(`| *(none - always on)* | - | ${toolsStr} |`);
}
console.log("\n## Usage\n");
console.log("Set environment variables to `false` to disable tool groups:\n");
console.log("```bash");
console.log("# Disable wiki tools");
console.log("USE_GITLAB_WIKI=false");
console.log("");
console.log("# Disable pipeline tools");
console.log("USE_PIPELINE=false");
console.log("```");
}
// ============================================================================
// Profile/Preset Inspection Functions
// ============================================================================
/**
* Mapping of feature flags to their corresponding tools.
* Used by countToolsForPreset and getToolsForPreset to filter tools based on features.
*/
const FEATURE_TO_TOOLS: Record<string, string[]> = {
wiki: ["browse_wiki", "manage_wiki"],
milestones: ["browse_milestones", "manage_milestone"],
pipelines: ["browse_pipelines", "manage_pipeline", "manage_pipeline_job"],
labels: ["browse_labels", "manage_label"],
mrs: [
"browse_merge_requests",
"browse_mr_discussions",
"manage_merge_request",
"manage_mr_discussion",
"manage_draft_notes",
],
files: ["browse_files", "manage_files"],
variables: ["browse_variables", "manage_variable"],
workitems: ["browse_work_items", "manage_work_item"],
webhooks: ["list_webhooks", "manage_webhook"],
snippets: ["browse_snippets", "manage_snippet"],
integrations: ["list_integrations", "manage_integration"],
};
/**
* List of all feature names, derived from FEATURE_TO_TOOLS keys.
* Used for feature display in preset details and comparisons.
*/
const FEATURE_NAMES = Object.keys(FEATURE_TO_TOOLS) as readonly string[];
/**
* Count tools enabled for a preset by simulating its application
*/
function countToolsForPreset(preset: Preset, allToolNames: string[]): number {
let enabledTools = allToolNames;
// Apply read_only filter (removes manage_* tools)
if (preset.read_only) {
enabledTools = enabledTools.filter(name => !name.startsWith("manage_"));
}
// Apply denied_tools_regex
if (preset.denied_tools_regex) {
try {
const regex = new RegExp(preset.denied_tools_regex);
enabledTools = enabledTools.filter(name => !regex.test(name));
} catch (error) {
console.warn(
`Warning: invalid denied_tools_regex "${preset.denied_tools_regex}": ${error instanceof Error ? error.message : "unknown error"}`
);
}
}
// Apply allowed_tools (whitelist overrides everything)
if (preset.allowed_tools && preset.allowed_tools.length > 0) {
const allowedSet = new Set(preset.allowed_tools);
enabledTools = enabledTools.filter(name => allowedSet.has(name));
}
// Apply feature flags
if (preset.features) {
for (const [feature, tools] of Object.entries(FEATURE_TO_TOOLS)) {
const featureKey = feature as keyof typeof preset.features;
if (preset.features[featureKey] === false) {
const toolSet = new Set(tools);
enabledTools = enabledTools.filter(name => !toolSet.has(name));
}
}
}
return enabledTools.length;
}
/**
* Get list of tools enabled/disabled by a preset
*/
function getToolsForPreset(
preset: Preset,
allToolNames: string[]
): { enabled: string[]; disabled: string[] } {
let enabledTools = [...allToolNames];
const disabledTools: string[] = [];
// Apply read_only filter
if (preset.read_only) {
const manageTools = enabledTools.filter(name => name.startsWith("manage_"));
disabledTools.push(...manageTools);
enabledTools = enabledTools.filter(name => !name.startsWith("manage_"));
}
// Apply denied_tools_regex
if (preset.denied_tools_regex) {
try {
const regex = new RegExp(preset.denied_tools_regex);
const denied = enabledTools.filter(name => regex.test(name));
disabledTools.push(...denied);
enabledTools = enabledTools.filter(name => !regex.test(name));
} catch (error) {
console.warn(
`Warning: invalid denied_tools_regex "${preset.denied_tools_regex}": ${error instanceof Error ? error.message : "unknown error"}`
);
}
}
// Apply allowed_tools (whitelist)
Iif (preset.allowed_tools && preset.allowed_tools.length > 0) {
const allowedSet = new Set(preset.allowed_tools);
const notAllowed = enabledTools.filter(name => !allowedSet.has(name));
disabledTools.push(...notAllowed);
enabledTools = enabledTools.filter(name => allowedSet.has(name));
}
// Apply feature flags
if (preset.features) {
for (const [feature, tools] of Object.entries(FEATURE_TO_TOOLS)) {
const featureKey = feature as keyof typeof preset.features;
if (preset.features[featureKey] === false) {
const toolSet = new Set(tools);
const disabled = enabledTools.filter(name => toolSet.has(name));
disabledTools.push(...disabled);
enabledTools = enabledTools.filter(name => !toolSet.has(name));
}
}
}
return {
enabled: enabledTools.sort(),
disabled: [...new Set(disabledTools)].sort(),
};
}
/**
* Print list of all presets in markdown format
*/
async function printPresetsList(
loader: ProfileLoader,
allToolNames: string[],
format: "markdown" | "json"
): Promise<void> {
const profiles = await loader.listProfiles();
const presets = profiles.filter(p => p.isPreset);
const userProfiles = profiles.filter(p => !p.isPreset);
if (format === "json") {
const output = {
builtIn: await Promise.all(
presets.map(async p => {
const preset = await loader.loadPreset(p.name);
return {
name: p.name,
description: p.description ?? "",
readOnly: p.readOnly,
toolCount: countToolsForPreset(preset, allToolNames),
};
})
),
userPresets: userProfiles.length, // Count only, no details for user profiles
totalTools: allToolNames.length,
};
console.log(JSON.stringify(output, null, 2));
return;
}
// Markdown format
console.log("# Available Presets\n");
console.log(`Total tools available: ${allToolNames.length}\n`);
console.log("## Built-in Presets\n");
console.log("| Preset | Tools | Read-Only | Description |");
console.log("|--------|-------|-----------|-------------|");
for (const p of presets) {
const preset = await loader.loadPreset(p.name);
const toolCount = countToolsForPreset(preset, allToolNames);
const ro = p.readOnly ? "Yes" : "No";
const desc = p.description ?? "-";
console.log(`| \`${p.name}\` | ${toolCount} | ${ro} | ${desc} |`);
}
if (userProfiles.length > 0) {
console.log("\n## User Profiles\n");
console.log(`${userProfiles.length} user profile(s) defined. Use \`--profiles\` to list them.`);
}
console.log("\nUse `yarn list-tools --preset <name>` for details.");
}
/**
* Print list of user profiles in markdown format
*/
async function printProfilesList(
loader: ProfileLoader,
format: "markdown" | "json"
): Promise<void> {
const profiles = await loader.listProfiles();
const userProfiles = profiles.filter(p => !p.isPreset);
if (format === "json") {
const output = userProfiles.map(p => ({
name: p.name,
host: p.host,
authType: p.authType,
readOnly: p.readOnly,
}));
console.log(JSON.stringify(output, null, 2));
return;
}
// Markdown format
console.log("# User Profiles\n");
if (userProfiles.length === 0) {
console.log("No user profiles defined.\n");
console.log("Create profiles in: `~/.config/gitlab-mcp/profiles.yaml`\n");
console.log("Example:\n");
console.log("```yaml");
console.log("profiles:");
console.log(" work:");
console.log(" host: gitlab.company.com");
console.log(" auth:");
console.log(" type: pat");
console.log(" token_env: GITLAB_WORK_TOKEN");
console.log("```");
return;
}
console.log("| Profile | Host | Auth | Read-Only |");
console.log("|---------|------|------|-----------|");
for (const p of userProfiles) {
const ro = p.readOnly ? "Yes" : "No";
console.log(`| \`${p.name}\` | ${p.host ?? "-"} | ${p.authType ?? "-"} | ${ro} |`);
}
console.log("\nUse `yarn list-tools --profile <name>` for details.");
}
/**
* Print detailed preset information
*/
async function printPresetDetails(
loader: ProfileLoader,
presetName: string,
allToolNames: string[],
format: "markdown" | "json",
validate: boolean
): Promise<void> {
let preset: Preset | undefined;
try {
preset = await loader.loadPreset(presetName);
} catch {
console.error(`Error: Preset '${presetName}' not found`);
process.exit(1);
return; // For test environment where process.exit is mocked
}
const { enabled, disabled } = getToolsForPreset(preset, allToolNames);
if (format === "json") {
const output: Record<string, unknown> = {
name: presetName,
type: "builtin",
description: preset.description ?? null,
readOnly: preset.read_only ?? false,
toolsEnabled: enabled.length,
toolsDisabled: disabled.length,
features: preset.features ?? {},
deniedToolsRegex: preset.denied_tools_regex ?? null,
allowedTools: preset.allowed_tools ?? null,
deniedActions: preset.denied_actions ?? null,
enabledTools: enabled,
disabledTools: disabled,
};
Iif (validate) {
const validation = await loader.validatePreset(preset);
output.validation = validation;
}
console.log(JSON.stringify(output, null, 2));
return;
}
// Markdown format
console.log(`# Preset: ${presetName}\n`);
console.log(`**Type:** Built-in`);
console.log(`**Description:** ${preset.description ?? "-"}`);
console.log(`**Tools Enabled:** ${enabled.length} (of ${allToolNames.length} available)`);
console.log(`**Read-Only:** ${preset.read_only ? "Yes" : "No"}\n`);
// Features table
if (preset.features) {
console.log("## Features\n");
console.log("| Feature | Status |");
console.log("|---------|--------|");
for (const f of FEATURE_NAMES) {
const featureKey = f as keyof typeof preset.features;
const status =
preset.features[featureKey] === true
? "Enabled"
: preset.features[featureKey] === false
? "Disabled"
: "-";
console.log(`| ${f} | ${status} |`);
}
console.log();
}
// Tool restrictions
console.log("## Tool Restrictions\n");
if (preset.denied_tools_regex) {
console.log(`**Denied tools regex:** \`${preset.denied_tools_regex}\`\n`);
}
Iif (preset.allowed_tools && preset.allowed_tools.length > 0) {
console.log(`**Allowed tools (whitelist):** ${preset.allowed_tools.length} tools\n`);
}
Iif (preset.denied_actions && preset.denied_actions.length > 0) {
console.log(`**Denied actions:** ${preset.denied_actions.join(", ")}\n`);
}
if (
!preset.denied_tools_regex &&
!preset.allowed_tools?.length &&
!preset.denied_actions?.length
) {
console.log("No explicit tool restrictions.\n");
}
// Enabled tools
console.log("## Enabled Tools\n");
for (const tool of enabled) {
console.log(`- ${tool}`);
}
console.log();
// Disabled tools (if any)
if (disabled.length > 0) {
console.log("## Disabled Tools\n");
for (const tool of disabled) {
console.log(`- ${tool}`);
}
console.log();
}
// Validation
if (validate) {
console.log("## Validation\n");
const validation = await loader.validatePreset(preset);
if (validation.valid && validation.warnings.length === 0) {
console.log("**Status: VALID**\n");
} else if (validation.valid) {
console.log(`**Status: VALID** (${validation.warnings.length} warning(s))\n`);
console.log("### Warnings\n");
for (const w of validation.warnings) {
console.log(`- ${w}`);
}
} else {
console.log(`**Status: INVALID** (${validation.errors.length} error(s))\n`);
console.log("### Errors\n");
for (const e of validation.errors) {
console.log(`- ${e}`);
}
Iif (validation.warnings.length > 0) {
console.log("\n### Warnings\n");
for (const w of validation.warnings) {
console.log(`- ${w}`);
}
}
}
}
}
/**
* Print detailed profile information
*/
async function printProfileDetails(
loader: ProfileLoader,
profileName: string,
format: "markdown" | "json",
validate: boolean
): Promise<void> {
let profile: Profile | undefined;
try {
profile = await loader.loadProfile(profileName);
} catch {
console.error(`Error: Profile '${profileName}' not found`);
process.exit(1);
return; // For test environment where process.exit is mocked
}
if (format === "json") {
const output: Record<string, unknown> = {
name: profileName,
type: "user",
host: profile.host,
authType: profile.auth.type,
readOnly: profile.read_only ?? false,
features: profile.features ?? {},
deniedToolsRegex: profile.denied_tools_regex ?? null,
allowedTools: profile.allowed_tools ?? null,
deniedActions: profile.denied_actions ?? null,
allowedProjects: profile.allowed_projects ?? null,
allowedGroups: profile.allowed_groups ?? null,
defaultProject: profile.default_project ?? null,
defaultNamespace: profile.default_namespace ?? null,
timeoutMs: profile.timeout_ms ?? null,
skipTlsVerify: profile.skip_tls_verify ?? false,
};
if (validate) {
const validation = await loader.validateProfile(profile);
output.validation = validation;
}
console.log(JSON.stringify(output, null, 2));
return;
}
// Markdown format
console.log(`# Profile: ${profileName}\n`);
console.log(`**Type:** User-defined`);
console.log(`**Host:** ${profile.host}`);
console.log(`**Auth:** ${profile.auth.type}`);
console.log(`**Read-Only:** ${profile.read_only ? "Yes" : "No"}\n`);
// Settings
console.log("## Settings\n");
console.log("| Setting | Value |");
console.log("|---------|-------|");
console.log(`| Timeout | ${profile.timeout_ms ?? "default"}ms |`);
console.log(`| TLS Verify | ${profile.skip_tls_verify ? "No" : "Yes"} |`);
if (profile.default_project) {
console.log(`| Default Project | ${profile.default_project} |`);
}
if (profile.default_namespace) {
console.log(`| Default Namespace | ${profile.default_namespace} |`);
}
console.log();
// Access restrictions
if (profile.allowed_projects?.length || profile.allowed_groups?.length) {
console.log("## Access Restrictions\n");
if (profile.allowed_projects?.length) {
console.log(`**Allowed Projects:** ${profile.allowed_projects.join(", ")}\n`);
}
if (profile.allowed_groups?.length) {
console.log(`**Allowed Groups:** ${profile.allowed_groups.join(", ")}\n`);
}
}
// Tool restrictions
if (
profile.denied_tools_regex ||
profile.allowed_tools?.length ||
profile.denied_actions?.length
) {
console.log("## Tool Restrictions\n");
if (profile.denied_tools_regex) {
console.log(`**Denied tools regex:** \`${profile.denied_tools_regex}\`\n`);
}
if (profile.allowed_tools?.length) {
console.log(`**Allowed tools (whitelist):** ${profile.allowed_tools.length} tools\n`);
}
if (profile.denied_actions?.length) {
console.log(`**Denied actions:** ${profile.denied_actions.join(", ")}\n`);
}
}
// Validation
if (validate) {
console.log("## Validation\n");
const validation = await loader.validateProfile(profile);
if (validation.valid && validation.warnings.length === 0) {
console.log("**Status: VALID**\n");
} else if (validation.valid) {
console.log(`**Status: VALID** (${validation.warnings.length} warning(s))\n`);
console.log("### Warnings\n");
for (const w of validation.warnings) {
console.log(`- ${w}`);
}
} else {
console.log(`**Status: INVALID** (${validation.errors.length} error(s))\n`);
console.log("### Errors\n");
for (const e of validation.errors) {
console.log(`- ${e}`);
}
}
}
}
/**
* Compare two presets
*/
async function comparePresets(
loader: ProfileLoader,
presetA: string,
presetB: string,
allToolNames: string[],
format: "markdown" | "json"
): Promise<void> {
let a: Preset | undefined, b: Preset | undefined;
try {
a = await loader.loadPreset(presetA);
} catch {
console.error(`Error: Preset '${presetA}' not found`);
process.exit(1);
return; // For test environment where process.exit is mocked
}
try {
b = await loader.loadPreset(presetB);
} catch {
console.error(`Error: Preset '${presetB}' not found`);
process.exit(1);
return; // For test environment where process.exit is mocked
}
const toolsA = getToolsForPreset(a, allToolNames);
const toolsB = getToolsForPreset(b, allToolNames);
const enabledSetA = new Set(toolsA.enabled);
const enabledSetB = new Set(toolsB.enabled);
const onlyInA = toolsA.enabled.filter(t => !enabledSetB.has(t));
const onlyInB = toolsB.enabled.filter(t => !enabledSetA.has(t));
const common = toolsA.enabled.filter(t => enabledSetB.has(t));
if (format === "json") {
const output = {
presetA: {
name: presetA,
description: a.description ?? null,
toolCount: toolsA.enabled.length,
readOnly: a.read_only ?? false,
},
presetB: {
name: presetB,
description: b.description ?? null,
toolCount: toolsB.enabled.length,
readOnly: b.read_only ?? false,
},
comparison: {
commonTools: common.length,
onlyInA: onlyInA.length,
onlyInB: onlyInB.length,
onlyInAList: onlyInA,
onlyInBList: onlyInB,
},
};
console.log(JSON.stringify(output, null, 2));
return;
}
// Markdown format
console.log(`# Comparison: ${presetA} vs ${presetB}\n`);
console.log("## Summary\n");
console.log("| | " + presetA + " | " + presetB + " |");
console.log("|---|---|---|");
console.log(`| Tools | ${toolsA.enabled.length} | ${toolsB.enabled.length} |`);
console.log(`| Read-Only | ${a.read_only ? "Yes" : "No"} | ${b.read_only ? "Yes" : "No"} |`);
console.log();
console.log(`**Common tools:** ${common.length}\n`);
Iif (onlyInA.length > 0) {
console.log(`## Only in ${presetA} (${onlyInA.length})\n`);
for (const t of onlyInA) {
console.log(`- ${t}`);
}
console.log();
}
Eif (onlyInB.length > 0) {
console.log(`## Only in ${presetB} (${onlyInB.length})\n`);
for (const t of onlyInB) {
console.log(`- ${t}`);
}
console.log();
}
// Feature comparison
Eif (a.features || b.features) {
console.log("## Feature Comparison\n");
console.log("| Feature | " + presetA + " | " + presetB + " |");
console.log("|---------|---|---|");
for (const f of FEATURE_NAMES) {
const featureKey = f as keyof typeof a.features;
const statusA =
a.features?.[featureKey] === true ? "Yes" : a.features?.[featureKey] === false ? "No" : "-";
const statusB =
b.features?.[featureKey] === true ? "Yes" : b.features?.[featureKey] === false ? "No" : "-";
if (statusA !== statusB) {
console.log(`| **${f}** | ${statusA} | ${statusB} |`);
} else {
console.log(`| ${f} | ${statusA} | ${statusB} |`);
}
}
}
}
export async function main() {
const options = parseArgs();
// Validate flag combinations
if (options.compare && !options.preset) {
console.error("Error: --compare flag must be used with --preset.");
console.error("Usage: yarn list-tools --preset <name> --compare <other_name>");
process.exit(1);
return;
}
if (options.validate && !options.preset && !options.profile) {
console.error("Error: --validate flag must be used with --preset or --profile.");
console.error("Usage: yarn list-tools --preset <name> --validate");
console.error(" or: yarn list-tools --profile <name> --validate");
process.exit(1);
return;
}
if (options.showEnv) {
printEnvironmentInfo();
}
// Get all tools from registry manager
const registryManager = RegistryManager.getInstance();
// Handle --env-gates flag
if (options.showEnvGates) {
const allTools = registryManager.getAllToolDefinitionsUnfiltered();
const gates = extractEnvGates(allTools);
const ungated = getUngatedTools(allTools);
printEnvGatesMarkdown(gates, ungated, options.format === "json" ? "json" : "markdown");
return;
}
// Handle profile/preset inspection flags (only instantiate when needed)
const needsProfileLoader =
Boolean(options.showPresets) ||
Boolean(options.showProfiles) ||
Boolean(options.preset) ||
Boolean(options.profile);
if (needsProfileLoader) {
const loader = new ProfileLoader();
const allToolNames = registryManager.getAllToolDefinitionsUnfiltered().map(t => t.name);
// --presets: List all presets
if (options.showPresets) {
await printPresetsList(loader, allToolNames, options.format === "json" ? "json" : "markdown");
return;
}
// --profiles: List user profiles
if (options.showProfiles) {
await printProfilesList(loader, options.format === "json" ? "json" : "markdown");
return;
}
// --preset <name> --compare <other>: Compare two presets
if (options.preset && options.compare) {
await comparePresets(
loader,
options.preset,
options.compare,
allToolNames,
options.format === "json" ? "json" : "markdown"
);
return;
}
// --preset <name>: Inspect a preset
if (options.preset) {
await printPresetDetails(
loader,
options.preset,
allToolNames,
options.format === "json" ? "json" : "markdown",
options.validate ?? false
);
return;
}
// --profile <name>: Inspect a profile
Eif (options.profile) {
await printProfileDetails(
loader,
options.profile,
options.format === "json" ? "json" : "markdown",
options.validate ?? false
);
return;
}
}
// For export mode: get ALL tools without filtering (for documentation)
// For other modes: respect env vars filtering
const toolDefinitions =
options.format === "export"
? registryManager.getAllToolDefinitionsUnfiltered()
: registryManager.getAllToolDefinitionsTierless();
const tools = toolDefinitions.map(def => ({
name: def.name,
description: def.description,
inputSchema: def.inputSchema,
}));
// Filter by entity if specified
let filteredTools = tools;
if (options.entity) {
const grouped = groupToolsByEntity(tools);
const entityKey = Array.from(grouped.keys()).find(
k => k.toLowerCase().replace(/ /g, "") === options.entity!.toLowerCase().replace(/ /g, "")
);
filteredTools = entityKey ? (grouped.get(entityKey) ?? []) : [];
Eif (filteredTools.length === 0) {
console.error(`No tools found for entity: ${options.entity}`);
process.exit(1);
}
}
// Filter by specific tool if specified
if (options.tool) {
filteredTools = filteredTools.filter(t => t.name === options.tool);
if (filteredTools.length === 0) {
console.error(`Tool not found: ${options.tool}`);
process.exit(1);
}
}
// Output based on format
switch (options.format) {
case "json":
const output = filteredTools.map(tool => ({
name: tool.name,
description: tool.description,
tier: ToolAvailability.getToolRequirement(tool.name)?.requiredTier ?? "unknown",
minVersion: ToolAvailability.getToolRequirement(tool.name)?.minVersion,
parameters: tool.inputSchema,
}));
console.log(JSON.stringify(output, null, 2));
break;
case "simple":
filteredTools.forEach(tool => {
console.log(tool.name);
});
break;
case "export":
const markdown = generateExportMarkdown(filteredTools, {
noExamples: options.noExamples,
toc: options.toc,
});
console.log(markdown);
break;
case "markdown":
default:
if (!options.entity && !options.tool) {
console.log("# GitLab MCP Tools\n");
console.log(`Total tools available: ${filteredTools.length}\n`);
const grouped = groupToolsByEntity(filteredTools);
// Show summary
console.log("## Categories\n");
for (const [entity, entityTools] of grouped) {
console.log(`- **${entity}**: ${entityTools.length} tools`);
}
console.log();
// Show tools by category
for (const [entity, entityTools] of grouped) {
console.log(`## ${entity}\n`);
for (const tool of entityTools) {
const tierInfo = getToolTierInfo(tool.name);
const tierDisplay = tierInfo ? ` ${tierInfo}` : "";
console.log(`### ${tool.name}${tierDisplay}`);
console.log(`**Description**: ${tool.description}\n`);
if ((options.verbose || options.detail) && tool.inputSchema) {
console.log("**Parameters**:");
const params = getParameterDescription(tool.inputSchema);
if (params.length > 0) {
params.forEach(p => console.log(p));
} else {
console.log(" (no parameters)");
}
console.log();
}
}
}
} else {
// Detailed view for filtered results
for (const tool of filteredTools) {
const tierInfo = getToolTierInfo(tool.name);
const tierDisplay = tierInfo ? ` ${tierInfo}` : "";
console.log(`## ${tool.name}${tierDisplay}\n`);
console.log(`**Description**: ${tool.description}\n`);
Eif (tool.inputSchema) {
console.log("**Parameters**:\n");
const params = getParameterDescription(tool.inputSchema);
if (params.length > 0) {
params.forEach(p => console.log(p));
} else {
console.log("(no parameters)");
}
}
console.log();
}
}
break;
}
if (options.showEnv && options.format === "markdown") {
console.log("\n---\n");
console.log("*Note: Tool availability may be affected by environment variables shown above.*");
}
}
// Auto-execute when script is run directly
Iif (!process.env.NODE_ENV || process.env.NODE_ENV !== "test") {
main().catch(error => {
console.error("Error:", error);
process.exit(1);
});
}
|