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 | 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 163x 163x 163x 163x 163x 163x 163x 163x 163x 163x 163x 163x 163x 357x 163x 355x 163x 163x 163x 159x 163x 162x 163x 162x 163x 162x 163x 162x 163x 162x 163x 162x 163x 161x 163x 162x 163x 162x 163x 162x 163x 9x 163x 9x 163x 9x 163x 9x 163x 163x 163x 9x 9x 163x 9x 163x 9x 163x 9x 163x 9x 163x 9x 163x 9x 163x 163x 163x 6x 6x 8x 30x 30x 30x 30x 28x 30x 29x 30x 29x 30x 29x 30x 29x 30x 29x 30x 29x 30x 29x 30x 29x 30x 29x 30x 29x 30x 7x 30x 7x 30x 7x 30x 7x 30x 30x 30x 7x 7x 30x 7x 30x 7x 30x 7x 30x 7x 30x 7x 30x 7x 30x 30x 2039x 2039x 1038x 1038x 1036x 4x 4x 4x 3x 3x 1x 1040x 5x 5x 239x 1040x 322x 322x 310x 12x 315x 310x 310x 315x 315x 310x 3x 5x 314x 14866x 14724x 14711x 14555x 14555x 12199x 2x 12197x 14236x 14236x 11622x 11620x 14233x 14866x 12489x 295x 295x 5753x 14124x 14124x 14124x 499x 499x 13625x 13625x 13418x 13418x 818x 13625x 13625x 13625x 7x 13625x 295x 295x 295x 13625x 13618x 13618x 827x 819x 475x 475x 432x 432x 430x 3x 3x 3x 253x 253x 253x 253x 10x 10x 253x 819x 819x 301x 301x 301x 301x 6x 2x 2x 4x 4x 4x 4x 4x 4x 295x 295x 295x 295x 295x 295x 295x 290x 5x 295x 126x 126x 126x 126x 124x 718x 2x 2x 128x 109x 43x 43x 11x 32x 32x 2x 2x 31x 126x 62x 62x 62x 62x 62x 62x 31x 31x 31x 1374x 1320x 31x 2x 29x 29x 29x 29x 31x 62x 1369x 23x 13x 427x 13x 427x 427x 427x 427x 13x 10x 10x 10x 10x 10x 4x 6x 6x 204x 6x 6x 6x 6x 1524x 1524x 1524x 1524x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 229x 511x 100x 411x 2x 409x 409x 409x 409x 409x 409x 9x 9x 348x 8x 348x 348x 348x 348x 52x 1x 61x 61x 61x 61x 46x 9x 5x 5x 135x 302x 5x 1x 27x 27x 45x 45x 45x 45x 45x 45x 40x 40x 1377x 40x 3x 37x 37x 5x 129x 129x 41x 41x 88x 20x 20x 20x 306x 770x 742x 742x 608x 134x 134x 20x 22x 22x 22x 22x 22x 22x 22x 1x 1x 21x 21x 2x 2x 2x 19x 19x 19x 19x 19x 22x 22x 334x 320x 320x 14x 35x 22x 17x 17x 21x | import { ToolRegistry, EnhancedToolDefinition, ToolDefinition } from './types';
import { coreToolRegistry, getCoreReadOnlyToolNames } from './entities/core/registry';
import { labelsToolRegistry, getLabelsReadOnlyToolNames } from './entities/labels/registry';
import { mrsToolRegistry, getMrsReadOnlyToolNames } from './entities/mrs/registry';
import { filesToolRegistry, getFilesReadOnlyToolNames } from './entities/files/registry';
import {
milestonesToolRegistry,
getMilestonesReadOnlyToolNames,
} from './entities/milestones/registry';
import {
pipelinesToolRegistry,
getPipelinesReadOnlyToolNames,
} from './entities/pipelines/registry';
import {
variablesToolRegistry,
getVariablesReadOnlyToolNames,
} from './entities/variables/registry';
import { wikiToolRegistry, getWikiReadOnlyToolNames } from './entities/wiki/registry';
import {
workitemsToolRegistry,
getWorkitemsReadOnlyToolNames,
} from './entities/workitems/registry';
import { webhooksToolRegistry, getWebhooksReadOnlyToolNames } from './entities/webhooks/registry';
import { snippetsToolRegistry, getSnippetsReadOnlyToolNames } from './entities/snippets/registry';
import {
integrationsToolRegistry,
getIntegrationsReadOnlyToolNames,
} from './entities/integrations/registry';
import { releasesToolRegistry, getReleasesReadOnlyToolNames } from './entities/releases/registry';
import { refsToolRegistry, getRefsReadOnlyToolNames } from './entities/refs/registry';
import { membersToolRegistry, getMembersReadOnlyToolNames } from './entities/members/registry';
import { searchToolRegistry, getSearchReadOnlyToolNames } from './entities/search/registry';
import { contextToolRegistry, getContextReadOnlyToolNames } from './entities/context/registry';
import {
iterationsToolRegistry,
getIterationsReadOnlyToolNames,
} from './entities/iterations/registry';
import {
jobTokenScopeToolRegistry,
getJobTokenScopeReadOnlyToolNames,
} from './entities/job-token-scope/registry';
import {
deployKeysToolRegistry,
getDeployKeysReadOnlyToolNames,
} from './entities/deploy-keys/registry';
import {
environmentsToolRegistry,
getEnvironmentsReadOnlyToolNames,
} from './entities/environments/registry';
import {
containerRegistryToolRegistry,
getContainerRegistryReadOnlyToolNames,
} from './entities/container_registry/registry';
import { runnersToolRegistry, getRunnersReadOnlyToolNames } from './entities/runners/registry';
import {
auditEventsToolRegistry,
getAuditEventsReadOnlyToolNames,
} from './entities/audit_events/registry';
import {
vulnerabilitiesToolRegistry,
getVulnerabilitiesReadOnlyToolNames,
} from './entities/vulnerabilities/registry';
import {
accessTokensToolRegistry,
getAccessTokensReadOnlyToolNames,
} from './entities/access_tokens/registry';
import {
GITLAB_BASE_URL,
GITLAB_READ_ONLY_MODE,
GITLAB_DENIED_TOOLS_REGEX,
GITLAB_CROSS_REFS,
USE_GITLAB_WIKI,
USE_MILESTONE,
USE_PIPELINE,
USE_WORKITEMS,
USE_LABELS,
USE_MRS,
USE_FILES,
USE_VARIABLES,
USE_SNIPPETS,
USE_WEBHOOKS,
USE_INTEGRATIONS,
USE_RELEASES,
USE_REFS,
USE_MEMBERS,
USE_SEARCH,
USE_ITERATIONS,
USE_CI_TOKENS,
USE_ENVIRONMENTS,
USE_REGISTRY,
USE_ACCESS_TOKENS,
USE_RUNNERS,
USE_AUDIT_EVENTS,
USE_VULNERABILITIES,
USE_DUO,
getToolDescriptionOverrides,
} from './config';
import {
isToolAvailable,
getRestrictedParameters,
getUnavailableActions,
type CapabilityGate,
} from './services/InstanceCapabilities';
import {
currentNamespaceTier,
hasNamespaceSubscriptions,
runWithNamespaceTier,
} from './services/namespace-tier-context';
import { ConnectionManager } from './services/ConnectionManager';
import { duoToolRegistry, getDuoReadOnlyToolNames } from './entities/duo/registry';
import type { EffectivePolicy, ToolFacts } from './configuration/policy';
import { HealthMonitor } from './services/HealthMonitor';
import { isToolAvailableForScopes } from './services/TokenScopeDetector';
import type { GitLabTier } from './services/GitLabVersionDetector';
import { logDebug, logError } from './logger';
import {
transformToolSchema,
stripTierRestrictedParameters,
shouldRemoveTool,
extractActionsFromSchema,
declaredArgumentNames,
flattenDiscriminatedUnion,
getSchemaMode,
type ClientSchemaMode,
} from './utils/schema-utils';
import { resolveRelatedReferences, stripRelatedSection } from './utils/description-utils';
import { normalizeInstanceUrl } from './utils/url';
import { groupOfRegistry } from './configuration/groups';
import { getGitLabApiUrlFromContext, getTokenContext } from './oauth/token-context';
import { isOAuthEnabled } from './oauth/config';
import { currentTokenAccount } from './accounts/token-account';
const NONE_UNAVAILABLE: ReadonlyMap<string, string> = new Map();
// The complete catalog and its read-only policy share the owning entity registries.
const ALL_REGISTRIES: ReadonlyArray<readonly [ToolRegistry, () => string[]]> = [
[coreToolRegistry, getCoreReadOnlyToolNames],
[contextToolRegistry, getContextReadOnlyToolNames],
[labelsToolRegistry, getLabelsReadOnlyToolNames],
[mrsToolRegistry, getMrsReadOnlyToolNames],
[filesToolRegistry, getFilesReadOnlyToolNames],
[milestonesToolRegistry, getMilestonesReadOnlyToolNames],
[pipelinesToolRegistry, getPipelinesReadOnlyToolNames],
[variablesToolRegistry, getVariablesReadOnlyToolNames],
[wikiToolRegistry, getWikiReadOnlyToolNames],
[workitemsToolRegistry, getWorkitemsReadOnlyToolNames],
[snippetsToolRegistry, getSnippetsReadOnlyToolNames],
[webhooksToolRegistry, getWebhooksReadOnlyToolNames],
[integrationsToolRegistry, getIntegrationsReadOnlyToolNames],
[releasesToolRegistry, getReleasesReadOnlyToolNames],
[refsToolRegistry, getRefsReadOnlyToolNames],
[membersToolRegistry, getMembersReadOnlyToolNames],
[searchToolRegistry, getSearchReadOnlyToolNames],
[iterationsToolRegistry, getIterationsReadOnlyToolNames],
[jobTokenScopeToolRegistry, getJobTokenScopeReadOnlyToolNames],
[deployKeysToolRegistry, getDeployKeysReadOnlyToolNames],
[environmentsToolRegistry, getEnvironmentsReadOnlyToolNames],
[containerRegistryToolRegistry, getContainerRegistryReadOnlyToolNames],
[accessTokensToolRegistry, getAccessTokensReadOnlyToolNames],
[runnersToolRegistry, getRunnersReadOnlyToolNames],
[auditEventsToolRegistry, getAuditEventsReadOnlyToolNames],
[vulnerabilitiesToolRegistry, getVulnerabilitiesReadOnlyToolNames],
[duoToolRegistry, getDuoReadOnlyToolNames],
];
/**
* Central registry manager that aggregates tools from all entity registries
* and provides a unified interface for tool discovery and execution
*/
class RegistryManager {
private static instance: RegistryManager;
private registries: Map<string, ToolRegistry> = new Map();
// Per-URL tool caches — each instance URL gets its own filtered tool map
// so concurrent multi-instance traffic cannot interfere (#379).
// Growth is bounded by the number of distinct GitLab instances (typically 1-3,
// never user-input-driven). No eviction needed at this scale.
private readonly toolLookupCaches = new Map<string, Map<string, EnhancedToolDefinition>>();
private readonly toolDefinitionsCaches = new Map<
string,
Map<ClientSchemaMode, ToolDefinition[]>
>();
private readonly toolNamesCaches = new Map<string, string[]>();
private readonly filterStatsCaches = new Map<string, FilterStats>();
// URLs where loadInstanceContext has returned a populated instanceInfo at
// least once. Caches built before ConnectionManager is ready (pre-init) are
// permissive (no tier/scope filtering) and must NOT be preserved on refresh
// failure — only verified caches should be kept as "last known good".
private readonly verifiedContextUrls = new Set<string>();
// Tool description overrides from environment variables
private descriptionOverrides: Map<string, string> = new Map();
// Cached read-only tools list built from registries
private readOnlyToolsCache: string[] | null = null;
private readOnlyToolSet: Set<string> | null = null;
private toolRegistryKeys: Map<string, string> | null = null;
private constructor() {
this.initializeRegistries();
this.loadDescriptionOverrides();
this.buildToolLookupCache();
}
public static getInstance(): RegistryManager {
if (!RegistryManager.instance) {
RegistryManager.instance = new RegistryManager();
}
return RegistryManager.instance;
}
/**
* Initialize all entity registries based on configuration
*/
private initializeRegistries(): void {
// Always add core tools
this.registries.set('core', coreToolRegistry);
// Always add context tools (runtime context management)
this.registries.set('context', contextToolRegistry);
// Add tools based on feature flags
if (USE_LABELS) {
this.registries.set('labels', labelsToolRegistry);
}
if (USE_MRS) {
this.registries.set('mrs', mrsToolRegistry);
}
if (USE_FILES) {
this.registries.set('files', filesToolRegistry);
}
if (USE_MILESTONE) {
this.registries.set('milestones', milestonesToolRegistry);
}
if (USE_PIPELINE) {
this.registries.set('pipelines', pipelinesToolRegistry);
}
if (USE_VARIABLES) {
this.registries.set('variables', variablesToolRegistry);
}
if (USE_GITLAB_WIKI) {
this.registries.set('wiki', wikiToolRegistry);
}
if (USE_WORKITEMS) {
this.registries.set('workitems', workitemsToolRegistry);
}
if (USE_SNIPPETS) {
this.registries.set('snippets', snippetsToolRegistry);
}
if (USE_WEBHOOKS) {
this.registries.set('webhooks', webhooksToolRegistry);
}
if (USE_INTEGRATIONS) {
this.registries.set('integrations', integrationsToolRegistry);
}
if (USE_RELEASES) {
this.registries.set('releases', releasesToolRegistry);
}
if (USE_REFS) {
this.registries.set('refs', refsToolRegistry);
}
if (USE_MEMBERS) {
this.registries.set('members', membersToolRegistry);
}
if (USE_SEARCH) {
this.registries.set('search', searchToolRegistry);
}
Eif (USE_ITERATIONS) {
this.registries.set('iterations', iterationsToolRegistry);
}
if (USE_CI_TOKENS) {
this.registries.set('job-token-scope', jobTokenScopeToolRegistry);
this.registries.set('deploy-keys', deployKeysToolRegistry);
}
if (USE_ENVIRONMENTS) {
this.registries.set('environments', environmentsToolRegistry);
}
if (USE_REGISTRY) {
this.registries.set('registry', containerRegistryToolRegistry);
}
if (USE_ACCESS_TOKENS) {
this.registries.set('access_tokens', accessTokensToolRegistry);
}
if (USE_RUNNERS) {
this.registries.set('runners', runnersToolRegistry);
}
if (USE_AUDIT_EVENTS) {
this.registries.set('audit_events', auditEventsToolRegistry);
}
if (USE_VULNERABILITIES) {
this.registries.set('vulnerabilities', vulnerabilitiesToolRegistry);
}
if (USE_DUO) this.registries.set('duo', duoToolRegistry);
// All entity registries have been migrated to the new pattern!
}
/**
* Load tool description overrides from environment variables
*/
private loadDescriptionOverrides(): void {
this.descriptionOverrides = getToolDescriptionOverrides();
if (this.descriptionOverrides.size > 0) {
logDebug('Loaded tool description overrides', { count: this.descriptionOverrides.size });
for (const [toolName, description] of this.descriptionOverrides) {
logDebug('Tool description override', { toolName, description });
}
}
}
/**
* Build read-only tools list from registries based on configuration
*/
private buildReadOnlyToolsList(): string[] {
const readOnlyTools: string[] = [];
// Always add core read-only tools
readOnlyTools.push(...getCoreReadOnlyToolNames());
// Always add context read-only tools
readOnlyTools.push(...getContextReadOnlyToolNames());
// Add read-only tools from enabled entities
if (USE_LABELS) {
readOnlyTools.push(...getLabelsReadOnlyToolNames());
}
if (USE_MRS) {
readOnlyTools.push(...getMrsReadOnlyToolNames());
}
if (USE_FILES) {
readOnlyTools.push(...getFilesReadOnlyToolNames());
}
if (USE_GITLAB_WIKI) {
readOnlyTools.push(...getWikiReadOnlyToolNames());
}
if (USE_MILESTONE) {
readOnlyTools.push(...getMilestonesReadOnlyToolNames());
}
if (USE_PIPELINE) {
readOnlyTools.push(...getPipelinesReadOnlyToolNames());
}
if (USE_WORKITEMS) {
readOnlyTools.push(...getWorkitemsReadOnlyToolNames());
}
if (USE_VARIABLES) {
readOnlyTools.push(...getVariablesReadOnlyToolNames());
}
if (USE_SNIPPETS) {
readOnlyTools.push(...getSnippetsReadOnlyToolNames());
}
if (USE_WEBHOOKS) {
readOnlyTools.push(...getWebhooksReadOnlyToolNames());
}
if (USE_INTEGRATIONS) {
readOnlyTools.push(...getIntegrationsReadOnlyToolNames());
}
if (USE_RELEASES) {
readOnlyTools.push(...getReleasesReadOnlyToolNames());
}
if (USE_REFS) {
readOnlyTools.push(...getRefsReadOnlyToolNames());
}
if (USE_MEMBERS) {
readOnlyTools.push(...getMembersReadOnlyToolNames());
}
if (USE_SEARCH) {
readOnlyTools.push(...getSearchReadOnlyToolNames());
}
Eif (USE_ITERATIONS) {
readOnlyTools.push(...getIterationsReadOnlyToolNames());
}
if (USE_CI_TOKENS) {
readOnlyTools.push(...getJobTokenScopeReadOnlyToolNames());
readOnlyTools.push(...getDeployKeysReadOnlyToolNames());
}
if (USE_ENVIRONMENTS) {
readOnlyTools.push(...getEnvironmentsReadOnlyToolNames());
}
if (USE_REGISTRY) {
readOnlyTools.push(...getContainerRegistryReadOnlyToolNames());
}
if (USE_ACCESS_TOKENS) {
readOnlyTools.push(...getAccessTokensReadOnlyToolNames());
}
if (USE_RUNNERS) {
readOnlyTools.push(...getRunnersReadOnlyToolNames());
}
if (USE_AUDIT_EVENTS) {
readOnlyTools.push(...getAuditEventsReadOnlyToolNames());
}
if (USE_VULNERABILITIES) {
readOnlyTools.push(...getVulnerabilitiesReadOnlyToolNames());
}
if (USE_DUO) readOnlyTools.push(...getDuoReadOnlyToolNames());
return readOnlyTools;
}
/**
* Get read-only tools list (cached for performance)
*/
private getReadOnlyTools(): string[] {
this.readOnlyToolsCache ??= this.buildReadOnlyToolsList();
return this.readOnlyToolsCache;
}
/** Whether the tool only reads GitLab (it stays available in read-only mode). */
public isReadOnlyTool(toolName: string): boolean {
this.readOnlyToolSet ??= new Set(this.getReadOnlyTools());
return this.readOnlyToolSet.has(toolName);
}
/** What the caller's settings need to know about a tool to allow or refuse it. */
public getToolFacts(toolName: string): ToolFacts {
return {
name: toolName,
group: groupOfRegistry(this.getToolRegistryKey(toolName)),
readOnly: this.isReadOnlyTool(toolName),
};
}
/**
* Names of the arguments a tool declares (across all its actions), or undefined when the
* tool or its arguments are unknown. The tool's handler drops any other argument.
*/
public getDeclaredArguments(toolName: string, action?: string): ReadonlySet<string> | undefined {
const key = this.getToolRegistryKey(toolName);
const tool = key === undefined ? undefined : this.registries.get(key)?.get(toolName);
if (!tool) return undefined;
const names = declaredArgumentNames(tool.inputSchema, action);
return names.size > 0 ? names : undefined;
}
/** Keys of the registries this server loaded (feature flags off are absent). */
public getRegistryKeys(): string[] {
return [...this.registries.keys()];
}
/** Key of the registry a tool belongs to (`mrs`, `wiki`, `core`, ...); undefined if unknown. */
public getToolRegistryKey(toolName: string): string | undefined {
if (!this.toolRegistryKeys) {
this.toolRegistryKeys = new Map();
for (const [key, registry] of this.registries) {
for (const name of registry.keys()) this.toolRegistryKeys.set(name, key);
}
}
return this.toolRegistryKeys.get(toolName);
}
/**
* Build unified tool lookup cache for O(1) tool access with filtering applied.
* @param instanceUrl — when provided, fetches tier/version/scopes for this
* specific instance URL instead of the default (currentInstanceUrl). Prevents
* cross-instance leakage when called from per-URL init/state-change events.
*/
/** Load instance context (tier/version/scopes) for cache build and stats.
* Returns undefined fields when connection is not initialized.
* @throws on unexpected errors (anything other than expected init errors). */
private loadInstanceContext(instanceUrl?: string): {
instanceInfo?: CapabilityGate;
tokenScopes?: readonly string[];
} {
let instanceInfo: CapabilityGate | undefined;
try {
const info = ConnectionManager.getInstance().getInstanceInfo(instanceUrl);
instanceInfo = { tier: info.tier, version: info.version };
} catch (err) {
if (!isExpectedInitError(err)) throw err;
}
// Admin-mode elevation (from the #434 probe) is what makes `requiresAdmin`
// parameter/tool gating take effect. The gate keys on active elevation, not the
// role, because admin-only endpoints 403 without it. Best-effort: any read failure
// leaves it undefined, which the gate treats as fail-open — a broken admin read
// must never hide tools or block the whole cache build.
if (instanceInfo) {
try {
instanceInfo.adminModeActive =
ConnectionManager.getInstance().getAdminInfo(instanceUrl)?.adminModeActive;
} catch (err) {
// getAdminInfo is a local cache read: only an uninitialized-connection
// error is expected (leaves elevation undefined = fail-open). Anything
// else (e.g. a renamed method) is a real bug — surface it.
if (!isExpectedInitError(err)) throw err;
}
}
let tokenScopes: readonly string[] | undefined;
try {
const scopeInfo = ConnectionManager.getInstance().getTokenScopeInfo(instanceUrl);
if (scopeInfo) {
tokenScopes = scopeInfo.scopes;
}
} catch (err) {
if (!isExpectedInitError(err)) throw err;
}
return { instanceInfo, tokenScopes };
}
/** Check if a tool should be included in the cache (passes all filters). */
/** Why a tool was excluded from the cache. Returns null if tool should be included.
* Used by both buildToolLookupCache and getFilterStats to ensure consistent logic. */
private getToolExclusionReason(
toolName: string,
tool: EnhancedToolDefinition,
ctx: {
instanceInfo?: CapabilityGate;
tokenScopes?: readonly string[];
},
unavailableActions: ReadonlyMap<string, string>,
): 'readOnly' | 'deniedRegex' | 'scopes' | 'tier' | 'admin' | 'actionDenial' | null {
if (GITLAB_READ_ONLY_MODE && !this.getReadOnlyTools().includes(toolName)) return 'readOnly';
if (GITLAB_DENIED_TOOLS_REGEX?.test(toolName)) return 'deniedRegex';
if (ctx.tokenScopes && !isToolAvailableForScopes(toolName, ctx.tokenScopes)) return 'scopes';
// Context tools (manage_context etc.) are always available regardless of
// GitLab version/tier — they are local/session tools, not GitLab API tools.
// Skip tier filtering for tools in the context registry.
const isContextTool = this.registries.get('context')?.has(toolName) ?? false;
if (!isContextTool && ctx.instanceInfo) {
// Admin-mode elevation is a distinct denial from tier/version: an admin-gated
// tool whose elevation is known inactive 403s regardless of version/tier, and
// the remediation differs (elevate admin mode vs upgrade tier). Bucket it
// separately before the tier check so getFilterStats/whoami stay accurate.
if (tool.requirements?.default.requiresAdmin && ctx.instanceInfo.adminModeActive === false)
return 'admin';
// No version-unknown short-circuit: isToolAvailable fail-opens version/tier
// internally when version is unknown but still enforces the admin gate, so an
// admin-only tool with inactive elevation is filtered even before detection lands.
if (!isToolAvailable(tool.requirements, ctx.instanceInfo)) return 'tier';
}
const allActions = extractActionsFromSchema(tool.inputSchema);
if (allActions.length > 0) {
if (shouldRemoveTool(toolName, allActions)) return 'actionDenial';
// Every action left is one the instance cannot serve.
if (shouldRemoveTool(toolName, allActions, unavailableActions)) return 'tier';
}
return null;
}
/** Actions of a GitLab-backed tool the instance cannot serve (none for context tools). */
private unavailableActionsFor(
toolName: string,
tool: EnhancedToolDefinition,
ctx: { instanceInfo?: CapabilityGate },
): ReadonlyMap<string, string> {
if (!ctx.instanceInfo || this.registries.get('context')?.has(toolName)) return NONE_UNAVAILABLE;
return getUnavailableActions(tool.requirements, ctx.instanceInfo);
}
/** Filter registries and build transformed tool map (schema + description overrides). */
private buildFilteredTools(ctx: {
instanceInfo?: CapabilityGate;
tokenScopes?: readonly string[];
}): Map<string, EnhancedToolDefinition> {
const result = new Map<string, EnhancedToolDefinition>();
for (const [, registry] of this.registries) {
for (const [toolName, tool] of registry) {
const unavailableActions = this.unavailableActionsFor(toolName, tool, ctx);
const exclusion = this.getToolExclusionReason(toolName, tool, ctx, unavailableActions);
if (exclusion) {
logDebug('Tool filtered out', { toolName, reason: exclusion });
continue;
}
// Store a canonical schema; client initialization must not mutate the shared cache.
let transformedSchema = transformToolSchema(
toolName,
tool.inputSchema,
unavailableActions,
'discriminated',
);
// Strip restricted parameters (skip only when not initialized). When version
// is unknown, getRestrictedParameters fail-opens version/tier but still strips
// admin-gated params whose elevation is known inactive.
if (ctx.instanceInfo) {
const restrictedParams = getRestrictedParameters(tool.requirements, ctx.instanceInfo);
if (restrictedParams.length > 0) {
transformedSchema = stripTierRestrictedParameters(transformedSchema, restrictedParams);
}
}
const customDescription = this.descriptionOverrides.get(toolName);
const finalTool = {
...tool,
inputSchema: transformedSchema,
...(customDescription && { description: customDescription }),
...(unavailableActions.size > 0 && { unavailableActions }),
};
if (customDescription) {
logDebug('Applied description override', { toolName, customDescription });
}
result.set(toolName, finalTool);
}
}
return result;
}
/** Resolve or strip Related: references in tool descriptions. */
private postProcessRelatedReferences(cache: Map<string, EnhancedToolDefinition>): void {
const availableToolNames = GITLAB_CROSS_REFS ? new Set(cache.keys()) : undefined;
for (const [toolName, tool] of cache) {
if (this.descriptionOverrides.has(toolName)) continue;
const nextDescription = availableToolNames
? resolveRelatedReferences(tool.description, availableToolNames)
: stripRelatedSection(tool.description);
if (nextDescription !== tool.description) {
cache.set(toolName, { ...tool, description: nextDescription });
}
}
}
/**
* Resolve the cache key for a given (or default) instance URL.
* Fallback chain: explicit URL → OAuth context → the configured instance a static-token
* chat switched to → (OAuth) getCurrentInstanceUrl() → GITLAB_BASE_URL.
* @param instanceUrl - Optional explicit instance URL
* @returns Normalized instance URL for use as cache key
*/
private resolveCacheUrl(instanceUrl?: string): string {
if (instanceUrl) return normalizeInstanceUrl(instanceUrl);
// Prefer OAuth request context URL (per-request, thread-safe) over the
// mutable getCurrentInstanceUrl() singleton which may belong to a different
// concurrent request.
const contextUrl = getGitLabApiUrlFromContext();
if (contextUrl) return normalizeInstanceUrl(contextUrl);
// A static-token chat lists its own instance, or the configured one it switched to.
const switched = currentTokenAccount()?.instanceUrl;
if (switched) return switched;
if (!isOAuthEnabled()) return normalizeInstanceUrl(GITLAB_BASE_URL);
try {
const current = ConnectionManager.getInstance().getCurrentInstanceUrl();
Eif (current) return normalizeInstanceUrl(current);
} catch {
// ConnectionManager not initialized yet — fall through to GITLAB_BASE_URL
}
return normalizeInstanceUrl(GITLAB_BASE_URL);
}
/**
* Resolve the per-URL cache for the given (or default) instance.
* Builds the cache on demand when it does not exist yet.
* @param instanceUrl - Optional instance URL to resolve the correct per-URL cache
* @returns The tool lookup cache for the resolved URL
*/
private resolveCache(instanceUrl?: string): Map<string, EnhancedToolDefinition> {
const url = this.resolveCacheUrl(instanceUrl);
const key = this.capabilityCacheKey(url);
let cache = this.toolLookupCaches.get(key);
if (!cache) {
this.buildToolLookupCache(url);
cache = this.toolLookupCaches.get(key);
}
return cache ?? new Map<string, EnhancedToolDefinition>();
}
/** At most three known subscription views per instance, plus the unknown view. */
private capabilityCacheKey(url: string): string {
const namespace = currentNamespaceTier(url);
return hasNamespaceSubscriptions(url) && namespace?.tier ? `${url}\0${namespace.tier}` : url;
}
private buildToolLookupCache(instanceUrl?: string): void {
const url = this.resolveCacheUrl(instanceUrl);
const key = this.capabilityCacheKey(url);
let ctx: ReturnType<RegistryManager['loadInstanceContext']>;
try {
ctx = this.loadInstanceContext(url);
} catch (err) {
if (this.verifiedContextUrls.has(key)) {
// Fail-close during refresh: preserve the previous verified cache
// instead of rebuilding with empty context (which would surface tools
// the instance cannot use). Pre-init caches (built before
// ConnectionManager was ready) are intentionally NOT preserved — they
// contain every tool unfiltered and should not be treated as "last
// known good".
logError('Unexpected error loading instance context; preserving previous cache', {
error: err instanceof Error ? err.message : String(err),
instanceUrl: url,
});
return;
}
// Do not leave a permissive pre-init snapshot live after an unexpected
// refresh failure. Callers (e.g. handlers.ts) may catch refreshCache()
// and continue serving whatever is still in the per-URL caches.
this.toolLookupCaches.delete(key);
this.toolDefinitionsCaches.delete(key);
this.toolNamesCaches.delete(key);
this.filterStatsCaches.delete(key);
// On cold start there is no prior cache to preserve. Fail fast so the
// process does not silently continue with no tools available.
logError('Unexpected error loading instance context; no previous cache available', {
error: err instanceof Error ? err.message : String(err),
instanceUrl: url,
});
throw err instanceof Error ? err : new Error(String(err));
}
// Build into a new map and swap atomically — prevents a concurrent
// refreshCache from clearing the live cache between hasToolHandler()
// and executeTool() in an in-flight request.
const newCache = this.buildFilteredTools(ctx);
this.postProcessRelatedReferences(newCache);
// A prior cache-miss failure may have seeded stale derived caches from the
// temporary empty Map returned by resolveCache(); drop them before swapping.
// filterStatsCaches is cleared here (not in invalidateCaches) so the last
// good snapshot survives if this rebuild was triggered by a failed refresh.
this.toolDefinitionsCaches.delete(key);
this.toolNamesCaches.delete(key);
this.filterStatsCaches.delete(key);
// Atomic per-URL swap — in-flight requests that captured a reference
// to the old map via getTool() keep working; new requests see the
// updated cache for this URL
this.toolLookupCaches.set(key, newCache);
// Track whether this cache was built with real context. Pre-init caches
// (built before ConnectionManager is ready) must not be preserved on
// failure. Updated AFTER swap so the flag describes the live cache.
if (ctx.instanceInfo) {
this.verifiedContextUrls.add(key);
} else {
this.verifiedContextUrls.delete(key);
}
logDebug('Registry manager built cache after filtering', {
toolCount: newCache.size,
instanceUrl: url,
});
}
/**
* Invalidate derived caches for a specific URL and rebuild lookup cache.
*/
private invalidateCaches(instanceUrl?: string): void {
const url = this.resolveCacheUrl(instanceUrl);
const currentKey = this.capabilityCacheKey(url);
const prefix = `${url}\0`;
// Each successful build replaces its view atomically. A failed refresh keeps
// its own verified snapshot, including descriptors and statistics.
this.buildToolLookupCache(url);
for (const key of this.toolLookupCaches.keys()) {
if (key === currentKey || (key !== url && !key.startsWith(prefix))) continue;
const tier = key === url ? null : (key.slice(prefix.length) as GitLabTier);
runWithNamespaceTier(url, tier, () => this.buildToolLookupCache(url));
}
}
/**
* Get a tool by name - O(1) lookup using per-URL cache.
* @param toolName - Tool name to look up
* @param instanceUrl - Optional instance URL to resolve the correct per-URL cache
*/
public getTool(
toolName: string,
instanceUrl?: string,
scopes?: readonly string[],
): EnhancedToolDefinition | null {
if (scopes && !isToolAvailableForScopes(toolName, scopes)) return null;
return this.resolveCache(instanceUrl).get(toolName) ?? null;
}
/**
* Execute a tool by name.
* @param toolName - Tool name to execute
* @param args - Tool arguments
* @param instanceUrl - Optional instance URL to resolve the correct per-URL cache
*/
public async executeTool(
toolName: string,
args: unknown,
instanceUrl?: string,
scopes?: readonly string[],
policy?: EffectivePolicy,
): Promise<unknown> {
const tool = this.getTool(toolName, instanceUrl, scopes);
if (!tool) {
throw new Error(`Tool '${toolName}' not found in any registry`);
}
// The schema no longer offers an action the instance cannot serve, but a
// client may still send it; refuse with the reason instead of calling GitLab.
const action = (args as { action?: unknown } | null)?.action;
if (tool.unavailableActions && typeof action === 'string') {
const reason = tool.unavailableActions.get(action.toLowerCase());
if (reason) throw new Error(`Action '${action}' of ${toolName} is unavailable: ${reason}`);
}
return policy === undefined ? await tool.handler(args) : await tool.handler(args, policy);
}
/**
* Clear all caches and rebuild (e.g., after ConnectionManager init provides tier/version).
* @param instanceUrl — optional URL to fetch tier/version/scopes from. Prevents
* the cache from resolving zero-arg defaults to a stale currentInstanceUrl.
*/
public refreshCache(instanceUrl?: string): void {
this.invalidateCaches(instanceUrl);
}
/**
* Get all tool definitions for a specific instance URL - cached per URL.
* @param instanceUrl - Optional instance URL. When omitted, resolves via
* OAuth request context → getCurrentInstanceUrl() → GITLAB_BASE_URL
*/
public getAllToolDefinitions(
instanceUrl?: string,
mode: ClientSchemaMode = getSchemaMode(),
scopes?: readonly string[],
): ToolDefinition[] {
// url (resolved) is used as cache key — always non-undefined.
// instanceUrl (raw) is passed to isUnreachableFor — preserves undefined
// so that no-arg callers hit the global "all instances down" branch,
// while explicit-URL callers get per-instance reachability.
const url = this.resolveCacheUrl(instanceUrl);
const cache = this.resolveCache(instanceUrl);
const unreachableMode = this.isUnreachableFor(instanceUrl);
// In unreachable mode, rebuild every call (transient state — don't cache
// a context-only list that would persist after recovery)
const key = this.capabilityCacheKey(url);
const cachedDefs = this.toolDefinitionsCaches.get(key)?.get(mode);
if (cachedDefs === undefined || unreachableMode) {
const contextTools = unreachableMode ? this.registries.get('context') : null;
const defs: ToolDefinition[] = [];
for (const tool of cache.values()) {
if (contextTools && !contextTools.has(tool.name)) continue;
defs.push(this.toToolDefinition(tool, mode));
}
// Don't persist cache in unreachable mode — next call after recovery
// should see full tool list
if (unreachableMode) {
return this.forScopes(defs, scopes);
}
const modes =
this.toolDefinitionsCaches.get(key) ?? new Map<ClientSchemaMode, ToolDefinition[]>();
modes.set(mode, defs);
this.toolDefinitionsCaches.set(key, modes);
return this.forScopes(defs, scopes);
}
return this.forScopes(cachedDefs, scopes);
}
private forScopes(definitions: ToolDefinition[], scopes?: readonly string[]): ToolDefinition[] {
// Account permissions are request data, never stored in a URL-keyed shared cache.
if (scopes === undefined) return definitions;
const filtered = definitions.filter((tool) => isToolAvailableForScopes(tool.name, scopes));
if (!GITLAB_CROSS_REFS || filtered.length === definitions.length) return filtered;
const availableNames = new Set<string>();
for (const tool of filtered) availableNames.add(tool.name);
for (let index = 0; index < filtered.length; index++) {
const tool = filtered[index];
Iif (this.descriptionOverrides.has(tool.name)) continue;
const description = resolveRelatedReferences(tool.description, availableNames);
// Only changed descriptions need ownership; never mutate the shared client-mode cache.
if (description !== tool.description) filtered[index] = { ...tool, description };
}
return filtered;
}
/**
* Get the full catalog of registered tool definitions for a specific instance URL,
* regardless of current connection health. Unlike {@link getAllToolDefinitions}, this
* method always returns the complete set from the tool lookup cache — it never applies
* the context-only filter used in unreachable mode.
*
* Use this for stable counts, metrics, and documentation where a transient connectivity
* issue should not reduce the reported tool count.
*
* @param instanceUrl - Optional instance URL. When omitted, resolves via
* OAuth request context → getCurrentInstanceUrl() → GITLAB_BASE_URL
*/
public getToolCatalog(
instanceUrl?: string,
mode: ClientSchemaMode = getSchemaMode(),
): ToolDefinition[] {
const url = this.resolveCacheUrl(instanceUrl);
const cache = this.resolveCache(instanceUrl);
const key = this.capabilityCacheKey(url);
const cachedDefs = this.toolDefinitionsCaches.get(key)?.get(mode);
// Return the cached full-list when available (same object already stored by
// getAllToolDefinitions on healthy path). If the cache is absent (e.g. first
// call, or was cleared after an invalidation) build it now without the
// unreachable-mode filter and persist it so the next call is O(1).
if (cachedDefs !== undefined) {
return cachedDefs;
}
const defs: ToolDefinition[] = [];
for (const tool of cache.values()) {
defs.push(this.toToolDefinition(tool, mode));
}
const modes =
this.toolDefinitionsCaches.get(key) ?? new Map<ClientSchemaMode, ToolDefinition[]>();
modes.set(mode, defs);
this.toolDefinitionsCaches.set(key, modes);
return defs;
}
private toToolDefinition(tool: EnhancedToolDefinition, mode: ClientSchemaMode): ToolDefinition {
const {
handler: _handler,
gate: _gate,
requirements: _requirements,
unavailableActions: _unavailable,
idempotent: _idempotent,
resultFormat: _format,
...definition
} = tool;
// Registry query membership is reviewed per entity; manage_context is deliberately
// allowed in GitLab read-only mode but mutates session state. Mixed CQRS commands
// remain conservative even when an individual action only reads.
const readOnly = this.getReadOnlyTools().includes(tool.name) && tool.name !== 'manage_context';
const label = tool.name.replaceAll('_', ' ');
return {
...definition,
title: tool.title ?? label.charAt(0).toUpperCase() + label.slice(1),
annotations: {
readOnlyHint: readOnly,
destructiveHint:
!readOnly && tool.name !== 'manage_context' && tool.name !== 'manage_todos',
openWorldHint: true,
idempotentHint: tool.idempotent ?? readOnly,
...tool.annotations,
},
inputSchema:
mode === 'flat' && definition.inputSchema.oneOf
? flattenDiscriminatedUnion(definition.inputSchema)
: definition.inputSchema,
};
}
/**
* Get tool definitions without GitLab tier/version filtering (for CLI tools, documentation, etc.)
* Dynamically checks environment filters at runtime to respect CLI-time environment variables
* but bypasses InstanceCapabilities tier/version checks since no GitLab connection exists
*/
public getAllToolDefinitionsTierless(): EnhancedToolDefinition[] {
const allTools: EnhancedToolDefinition[] = [];
// Dynamically check environment variables at runtime
const isReadOnly = process.env.GITLAB_READ_ONLY_MODE === 'true';
const deniedRegex = process.env.GITLAB_DENIED_TOOLS_REGEX
? new RegExp(process.env.GITLAB_DENIED_TOOLS_REGEX)
: undefined;
// Dynamically check USE_* flags at runtime
const useLabels = process.env.USE_LABELS !== 'false';
const useMrs = process.env.USE_MRS !== 'false';
const useFiles = process.env.USE_FILES !== 'false';
const useMilestone = process.env.USE_MILESTONE !== 'false';
const usePipeline = process.env.USE_PIPELINE !== 'false';
const useVariables = process.env.USE_VARIABLES !== 'false';
const useWiki = process.env.USE_GITLAB_WIKI !== 'false';
const useWorkitems = process.env.USE_WORKITEMS !== 'false';
const useSnippets = process.env.USE_SNIPPETS !== 'false';
const useWebhooks = process.env.USE_WEBHOOKS !== 'false';
const useIntegrations = process.env.USE_INTEGRATIONS !== 'false';
const useReleases = process.env.USE_RELEASES !== 'false';
const useRefs = process.env.USE_REFS !== 'false';
const useMembers = process.env.USE_MEMBERS !== 'false';
const useSearch = process.env.USE_SEARCH !== 'false';
const useIterations = process.env.USE_ITERATIONS !== 'false';
const useCiTokens = process.env.USE_CI_TOKENS !== 'false';
const useEnvironments = process.env.USE_ENVIRONMENTS !== 'false';
const useRegistry = process.env.USE_REGISTRY !== 'false';
const useAccessTokens = process.env.USE_ACCESS_TOKENS !== 'false';
const useRunners = process.env.USE_RUNNERS !== 'false';
const useAuditEvents = process.env.USE_AUDIT_EVENTS !== 'false';
const useVulnerabilities = process.env.USE_VULNERABILITIES !== 'false';
// Build registries map based on dynamic feature flags
const registriesToUse = new Map<string, ToolRegistry>();
// Always add core tools
registriesToUse.set('core', coreToolRegistry);
// Always add context tools
registriesToUse.set('context', contextToolRegistry);
// Add tools based on dynamically checked feature flags
if (useLabels) registriesToUse.set('labels', labelsToolRegistry);
if (useMrs) registriesToUse.set('mrs', mrsToolRegistry);
if (useFiles) registriesToUse.set('files', filesToolRegistry);
if (useMilestone) registriesToUse.set('milestones', milestonesToolRegistry);
if (usePipeline) registriesToUse.set('pipelines', pipelinesToolRegistry);
if (useVariables) registriesToUse.set('variables', variablesToolRegistry);
if (useWiki) registriesToUse.set('wiki', wikiToolRegistry);
if (useWorkitems) registriesToUse.set('workitems', workitemsToolRegistry);
if (useSnippets) registriesToUse.set('snippets', snippetsToolRegistry);
if (useWebhooks) registriesToUse.set('webhooks', webhooksToolRegistry);
if (useIntegrations) registriesToUse.set('integrations', integrationsToolRegistry);
Eif (useReleases) registriesToUse.set('releases', releasesToolRegistry);
Eif (useRefs) registriesToUse.set('refs', refsToolRegistry);
Eif (useMembers) registriesToUse.set('members', membersToolRegistry);
Eif (useSearch) registriesToUse.set('search', searchToolRegistry);
Eif (useIterations) registriesToUse.set('iterations', iterationsToolRegistry);
Eif (useCiTokens) {
registriesToUse.set('job-token-scope', jobTokenScopeToolRegistry);
registriesToUse.set('deploy-keys', deployKeysToolRegistry);
}
Eif (useEnvironments) registriesToUse.set('environments', environmentsToolRegistry);
Eif (useRegistry) registriesToUse.set('registry', containerRegistryToolRegistry);
Eif (useAccessTokens) registriesToUse.set('access_tokens', accessTokensToolRegistry);
Eif (useRunners) registriesToUse.set('runners', runnersToolRegistry);
Eif (useAuditEvents) registriesToUse.set('audit_events', auditEventsToolRegistry);
Eif (useVulnerabilities) registriesToUse.set('vulnerabilities', vulnerabilitiesToolRegistry);
if (process.env.USE_DUO !== 'false') registriesToUse.set('duo', duoToolRegistry);
// Dynamically load description overrides
const descOverrides = getToolDescriptionOverrides();
for (const registry of registriesToUse.values()) {
for (const [toolName, tool] of registry) {
// Apply dynamically checked GITLAB_READ_ONLY_MODE filtering
if (isReadOnly && !this.getReadOnlyTools().includes(toolName)) {
continue;
}
// Apply dynamically checked GITLAB_DENIED_TOOLS_REGEX filtering
if (deniedRegex?.test(toolName)) {
continue;
}
// Check if all actions are denied for this CQRS tool
const allActions = extractActionsFromSchema(tool.inputSchema);
Iif (allActions.length > 0 && shouldRemoveTool(toolName, allActions)) {
continue;
}
// Transform schema to remove denied actions and apply description overrides
const transformedSchema = transformToolSchema(toolName, tool.inputSchema);
// Apply dynamically loaded description override if available
const customDescription = descOverrides.get(toolName);
const finalTool: EnhancedToolDefinition = {
...tool,
inputSchema: transformedSchema,
...(customDescription && { description: customDescription }),
};
allTools.push(finalTool);
}
}
// Second pass: handle Related references based on GITLAB_CROSS_REFS setting
const crossRefsEnabled = process.env.GITLAB_CROSS_REFS !== 'false';
if (crossRefsEnabled) {
// Resolve Related references against available tools
const availableToolNames = new Set(allTools.map((t) => t.name));
for (let i = 0; i < allTools.length; i++) {
const tool = allTools[i];
// Skip tools with custom description overrides
Iif (descOverrides.has(tool.name)) continue;
const resolved = resolveRelatedReferences(tool.description, availableToolNames);
if (resolved !== tool.description) {
allTools[i] = { ...tool, description: resolved };
}
}
} else {
// Cross-refs disabled: strip all "Related:" sections entirely
for (let i = 0; i < allTools.length; i++) {
const tool = allTools[i];
Iif (descOverrides.has(tool.name)) continue;
const stripped = stripRelatedSection(tool.description);
if (stripped !== tool.description) {
allTools[i] = { ...tool, description: stripped };
}
}
}
return allTools;
}
/**
* Returns ALL tool definitions without any filtering or transformation.
* Used for documentation generation (--export) where we need:
* - Complete tool catalog regardless of environment configuration
* - Original discriminated union schemas for rich action descriptions
*/
public getAllToolDefinitionsUnfiltered(): EnhancedToolDefinition[] {
const allTools: EnhancedToolDefinition[] = [];
for (const [registry] of ALL_REGISTRIES) {
for (const [, tool] of registry) {
// Return original schema without transformation
// This preserves discriminated union structure for documentation
allTools.push(tool);
}
}
return allTools;
}
/** Complete publication catalog, independent of instance, account and feature filters. */
public getUnfilteredCatalog(): {
tools: EnhancedToolDefinition[];
toolGroupCount: number;
readOnlyToolNames: string[];
} {
return {
tools: this.getAllToolDefinitionsUnfiltered(),
toolGroupCount: ALL_REGISTRIES.length,
readOnlyToolNames: ALL_REGISTRIES.flatMap(([, names]) => names()),
};
}
/**
* Check if a tool exists in the per-URL cache - O(1) lookup.
* @param toolName - Tool name to check
* @param instanceUrl - Optional instance URL to resolve the correct per-URL cache
*/
public hasToolHandler(toolName: string, instanceUrl?: string): boolean {
return this.resolveCache(instanceUrl).has(toolName);
}
/**
* Get all available tool names for a specific instance URL - cached per URL.
* @param instanceUrl - Optional instance URL. When omitted, resolves via
* OAuth request context → getCurrentInstanceUrl() → GITLAB_BASE_URL
*/
public getAvailableToolNames(instanceUrl?: string): string[] {
// See getAllToolDefinitions for url vs instanceUrl rationale
const url = this.resolveCacheUrl(instanceUrl);
const cache = this.resolveCache(instanceUrl);
const unreachableMode = this.isUnreachableFor(instanceUrl);
const key = this.capabilityCacheKey(url);
const cachedNames = this.toolNamesCaches.get(key);
if (cachedNames === undefined || unreachableMode) {
const contextTools = unreachableMode ? this.registries.get('context') : null;
const names = Array.from(cache.keys()).filter(
(name) => !contextTools || contextTools.has(name),
);
if (unreachableMode) {
return names;
}
this.toolNamesCaches.set(key, names);
return names;
}
return cachedNames;
}
/**
* Check if the given (or all) instances are unreachable.
* When instanceUrl is provided, checks per-URL reachability.
* When omitted, falls back to the global "all instances down" check.
* @param instanceUrl - Optional instance URL for per-URL check
* @returns True when the instance (or all instances) are unreachable
*/
private isUnreachableFor(instanceUrl?: string): boolean {
const healthMonitor = HealthMonitor.getInstance();
if (instanceUrl) {
try {
// isInstanceReachable returns false for 'connecting', but we treat
// connecting as reachable (optimistic during startup/reconnect)
return (
!healthMonitor.isInstanceReachable(instanceUrl) &&
healthMonitor.getState(instanceUrl) !== 'connecting'
);
} catch {
// HealthMonitor not initialized or URL not tracked — assume reachable
return false;
}
}
// Global fallback: all instances down
return (
healthMonitor.getMonitoredInstances().length > 0 && !healthMonitor.isAnyInstanceHealthy()
);
}
/**
* Aggregate per-tool exclusion counts across all registries.
* Extracted from getFilterStats to keep cognitive complexity within limits.
*/
private aggregateFilterCounters(
ctx: ReturnType<RegistryManager['loadInstanceContext']>,
contextTools: Map<string, EnhancedToolDefinition> | null | undefined,
): {
available: number;
byReadOnly: number;
byDeniedRegex: number;
byScopes: number;
byTier: number;
byActionDenial: number;
byAdmin: number;
} {
const counts = {
available: 0,
byReadOnly: 0,
byDeniedRegex: 0,
byScopes: 0,
byTier: 0,
byActionDenial: 0,
byAdmin: 0,
};
const counterByReason: Record<string, keyof typeof counts> = {
readOnly: 'byReadOnly',
deniedRegex: 'byDeniedRegex',
scopes: 'byScopes',
tier: 'byTier',
actionDenial: 'byActionDenial',
admin: 'byAdmin',
};
for (const registry of this.registries.values()) {
for (const [toolName, tool] of registry) {
if (contextTools && !contextTools.has(toolName)) continue;
const reason = this.getToolExclusionReason(
toolName,
tool,
ctx,
this.unavailableActionsFor(toolName, tool, ctx),
);
if (!reason) {
counts.available++;
} else {
const key = counterByReason[reason];
Eif (key) counts[key]++;
}
}
}
return counts;
}
/**
* Get filter statistics showing how tools were filtered
* Used by whoami action to explain tool availability
*/
public getFilterStats(instanceUrl?: string): FilterStats {
const accountScopes = getTokenContext()?.gitlabScopes;
// See getAllToolDefinitions for url vs instanceUrl rationale:
// raw instanceUrl for reachability (preserves undefined → global fallback),
// resolved url for instance context loading (avoids currentInstanceUrl leakage).
const url = this.resolveCacheUrl(instanceUrl);
const key = this.capabilityCacheKey(url);
const unreachableMode = this.isUnreachableFor(instanceUrl);
const contextTools = unreachableMode ? this.registries.get('context') : null;
// Count total tools — in unreachable mode, only context tools are in scope
const totalTools = this.countCatalogTools(contextTools);
// In unreachable mode, tier/scope context is irrelevant — only context
// tools are shown. Skip loadInstanceContext but still apply local filters
// (readOnly, deniedRegex, actionDenial) so stats stay consistent with
// the actual tool list returned by getAllToolDefinitions().
if (unreachableMode) {
const { available, byReadOnly, byDeniedRegex, byActionDenial } = this.aggregateFilterCounters(
{},
contextTools,
);
return {
available,
total: totalTools,
filteredByScopes: 0,
filteredByReadOnly: byReadOnly,
filteredByTier: 0,
filteredByDeniedRegex: byDeniedRegex,
filteredByActionDenial: byActionDenial,
filteredByAdmin: 0,
};
}
// Re-run filter logic with per-URL context — uses the resolved URL
// so instance info/scopes match the same URL that caches are keyed by.
let ctx: ReturnType<RegistryManager['loadInstanceContext']>;
try {
ctx = this.loadInstanceContext(url);
} catch (err) {
// Fail-close: return the last successful FilterStats for this URL so
// the total = available + filtered invariant is preserved. If no prior
// stats exist, return a conservative snapshot (available=0, all tools
// attributed to filteredByScopes) to maintain the invariant.
logError('Unexpected error loading instance context for filter stats; using cached stats', {
error: err instanceof Error ? err.message : String(err),
instanceUrl: url,
});
// Fallback: cached stats from last successful run, or a conservative
// object that reports all tools as filtered (available=0) while still
// reflecting the real total so whoami doesn't show totalToolCount: 0.
const filteredTotal = totalTools;
return (
(accountScopes === undefined ? this.filterStatsCaches.get(key) : undefined) ?? {
available: 0,
total: filteredTotal,
filteredByScopes: filteredTotal,
filteredByReadOnly: 0,
filteredByTier: 0,
filteredByDeniedRegex: 0,
filteredByActionDenial: 0,
filteredByAdmin: 0,
}
);
}
if (accountScopes !== undefined) ctx = { ...ctx, tokenScopes: accountScopes };
const {
available: availableTools,
byReadOnly: filteredByReadOnly,
byDeniedRegex: filteredByDeniedRegex,
byScopes: filteredByScopes,
byTier: filteredByTier,
byActionDenial: filteredByActionDenial,
byAdmin: filteredByAdmin,
} = this.aggregateFilterCounters(ctx, contextTools);
const stats: FilterStats = {
available: availableTools,
total: totalTools,
filteredByScopes,
filteredByReadOnly,
filteredByTier,
filteredByDeniedRegex,
filteredByActionDenial,
filteredByAdmin,
};
if (accountScopes === undefined) this.filterStatsCaches.set(key, stats);
return stats;
}
private countCatalogTools(
contextTools: ReadonlyMap<string, EnhancedToolDefinition> | null | undefined,
): number {
let total = 0;
for (const registry of this.registries.values()) {
if (!contextTools) {
total += registry.size;
continue;
}
for (const name of registry.keys()) {
if (contextTools.has(name)) total++;
}
}
return total;
}
}
/** Return true for errors that indicate the ConnectionManager is not yet
* initialised (expected during startup / before first connection). */
function isExpectedInitError(err: unknown): boolean {
const msg = err instanceof Error ? err.message : String(err);
return (
msg.includes('not initialized') ||
msg.includes('not available') ||
msg.includes('No connection')
);
}
/**
* Filter statistics interface
*/
export interface FilterStats {
/** Number of tools available after filtering */
available: number;
/** Total number of registered tools */
total: number;
/** Tools filtered due to insufficient token scopes */
filteredByScopes: number;
/** Tools filtered due to read-only mode */
filteredByReadOnly: number;
/** Tools filtered due to GitLab tier/version restrictions */
filteredByTier: number;
/** Tools filtered due to denied tools regex */
filteredByDeniedRegex: number;
/** Tools filtered due to all actions being denied */
filteredByActionDenial: number;
/** Tools filtered due to inactive admin-mode elevation (distinct from tier/version) */
filteredByAdmin: number;
}
export { RegistryManager };
|