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 | 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 126x 131x 126x 129x 126x 126x 126x 123x 126x 125x 126x 125x 126x 125x 126x 125x 126x 125x 126x 125x 126x 124x 126x 125x 126x 125x 126x 125x 126x 5x 126x 5x 126x 5x 126x 5x 126x 126x 126x 126x 6x 6x 8x 10x 10x 10x 10x 8x 10x 9x 10x 9x 10x 9x 10x 9x 10x 9x 10x 9x 10x 9x 10x 9x 10x 9x 10x 9x 10x 10x 10x 10x 10x 10x 10x 389x 389x 148x 148x 137x 11x 141x 141x 136x 3x 5x 140x 4126x 3974x 3961x 3874x 3874x 9x 3865x 3865x 3863x 131x 131x 1840x 3854x 3854x 199x 199x 3655x 3655x 3534x 3534x 1x 3655x 3655x 3655x 7x 3655x 131x 131x 131x 3655x 3648x 3648x 210x 282x 262x 262x 259x 259x 259x 76x 76x 76x 4x 4x 76x 137x 137x 137x 6x 2x 2x 4x 4x 4x 4x 4x 4x 131x 131x 131x 131x 131x 131x 131x 127x 4x 131x 7x 7x 7x 7x 22x 3x 3x 1x 2x 7x 18x 18x 18x 18x 18x 14x 14x 14x 353x 295x 14x 2x 12x 12x 4x 2x 2x 2x 2x 2x 2x 60x 2x 2x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 131x 270x 51x 219x 2x 217x 217x 217x 217x 217x 217x 8x 8x 178x 7x 178x 178x 178x 178x 31x 1x 39x 39x 39x 39x 32x 8x 2x 2x 2x 36x 74x 2x 4x 30x 30x 30x 30x 30x 27x 27x 724x 27x 2x 25x 25x 3x 60x 60x 5x 5x 55x 10x 10x 10x 140x 301x 272x 272x 208x 64x 64x 10x 12x 12x 12x 12x 12x 168x 361x 332x 12x 1x 1x 11x 11x 2x 2x 2x 9x 9x 9x 9x 16x 16x 16x | 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 {
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,
getToolDescriptionOverrides,
} from './config';
import { ToolAvailability } from './services/ToolAvailability';
import { ConnectionManager } from './services/ConnectionManager';
import { HealthMonitor } from './services/HealthMonitor';
import { isToolAvailableForScopes } from './services/TokenScopeDetector';
import type { GitLabScope } from './services/TokenScopeDetector';
import type { GitLabTier } from './services/GitLabVersionDetector';
import { logDebug, logError } from './logger';
import {
transformToolSchema,
stripTierRestrictedParameters,
shouldRemoveTool,
extractActionsFromSchema,
} from './utils/schema-utils';
import { resolveRelatedReferences, stripRelatedSection } from './utils/description-utils';
import { normalizeInstanceUrl } from './utils/url';
import { getGitLabApiUrlFromContext } from './oauth/token-context';
/**
* 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, 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 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);
}
// 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());
}
Iif (USE_RELEASES) {
readOnlyTools.push(...getReleasesReadOnlyToolNames());
}
Iif (USE_REFS) {
readOnlyTools.push(...getRefsReadOnlyToolNames());
}
Iif (USE_MEMBERS) {
readOnlyTools.push(...getMembersReadOnlyToolNames());
}
Iif (USE_SEARCH) {
readOnlyTools.push(...getSearchReadOnlyToolNames());
}
Eif (USE_ITERATIONS) {
readOnlyTools.push(...getIterationsReadOnlyToolNames());
}
return readOnlyTools;
}
/**
* Get read-only tools list (cached for performance)
*/
private getReadOnlyTools(): string[] {
this.readOnlyToolsCache ??= this.buildReadOnlyToolsList();
return this.readOnlyToolsCache;
}
/**
* 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?: { tier: GitLabTier; version: string };
tokenScopes?: GitLabScope[];
} {
let instanceInfo: { tier: GitLabTier; version: string } | undefined;
try {
const info = ConnectionManager.getInstance().getInstanceInfo(instanceUrl);
instanceInfo = { tier: info.tier, version: info.version };
} catch (err) {
if (!isExpectedInitError(err)) throw err;
}
let tokenScopes: GitLabScope[] | 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?: { tier: GitLabTier; version: string }; tokenScopes?: GitLabScope[] },
): 'readOnly' | 'deniedRegex' | 'scopes' | 'tier' | '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 &&
ctx.instanceInfo.version !== 'unknown' &&
!ToolAvailability.isToolAvailableForInstance(toolName, ctx.instanceInfo)
)
return 'tier';
const allActions = extractActionsFromSchema(tool.inputSchema);
if (allActions.length > 0 && shouldRemoveTool(toolName, allActions)) return 'actionDenial';
return null;
}
/** Filter registries and build transformed tool map (schema + description overrides). */
private buildFilteredTools(ctx: {
instanceInfo?: { tier: GitLabTier; version: string };
tokenScopes?: GitLabScope[];
}): Map<string, EnhancedToolDefinition> {
const result = new Map<string, EnhancedToolDefinition>();
for (const [, registry] of this.registries) {
for (const [toolName, tool] of registry) {
const exclusion = this.getToolExclusionReason(toolName, tool, ctx);
if (exclusion) {
logDebug('Tool filtered out', { toolName, reason: exclusion });
continue;
}
let transformedSchema = transformToolSchema(toolName, tool.inputSchema);
// Strip tier-restricted parameters (skip when version unknown or not initialized)
if (ctx.instanceInfo && ctx.instanceInfo.version !== 'unknown') {
const restrictedParams = ToolAvailability.getRestrictedParameters(
toolName,
ctx.instanceInfo,
);
if (restrictedParams.length > 0) {
transformedSchema = stripTierRestrictedParameters(transformedSchema, restrictedParams);
}
}
const customDescription = this.descriptionOverrides.get(toolName);
const finalTool = {
...tool,
inputSchema: transformedSchema,
...(customDescription && { description: customDescription }),
};
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 → 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);
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);
let cache = this.toolLookupCaches.get(url);
if (!cache) {
this.buildToolLookupCache(url);
cache = this.toolLookupCaches.get(url);
}
return cache ?? new Map<string, EnhancedToolDefinition>();
}
private buildToolLookupCache(instanceUrl?: string): void {
const url = this.resolveCacheUrl(instanceUrl);
let ctx: ReturnType<RegistryManager['loadInstanceContext']>;
try {
ctx = this.loadInstanceContext(url);
} catch (err) {
if (this.verifiedContextUrls.has(url)) {
// 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(url);
this.toolDefinitionsCaches.delete(url);
this.toolNamesCaches.delete(url);
this.filterStatsCaches.delete(url);
// 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(url);
this.toolNamesCaches.delete(url);
this.filterStatsCaches.delete(url);
// 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(url, 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(url);
} else {
this.verifiedContextUrls.delete(url);
}
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);
this.toolDefinitionsCaches.delete(url);
this.toolNamesCaches.delete(url);
// filterStatsCaches is intentionally NOT cleared here — it is preserved
// until buildToolLookupCache succeeds, so getFilterStats can fall back to
// the last good snapshot if the rebuild fails mid-way.
// readOnlyToolsCache is derived from registries + config flags (USE_*),
// not from instance URL — no need to clear on per-URL refresh.
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): EnhancedToolDefinition | 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,
): Promise<unknown> {
const tool = this.getTool(toolName, instanceUrl);
if (!tool) {
throw new Error(`Tool '${toolName}' not found in any registry`);
}
return await tool.handler(args);
}
/**
* 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): 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 cachedDefs = this.toolDefinitionsCaches.get(url);
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({
name: tool.name,
description: tool.description,
inputSchema: tool.inputSchema,
});
}
// Don't persist cache in unreachable mode — next call after recovery
// should see full tool list
if (unreachableMode) {
return defs;
}
this.toolDefinitionsCaches.set(url, defs);
return defs;
}
return cachedDefs;
}
/**
* 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): ToolDefinition[] {
const url = this.resolveCacheUrl(instanceUrl);
const cache = this.resolveCache(instanceUrl);
const cachedDefs = this.toolDefinitionsCaches.get(url);
// 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).
Iif (cachedDefs !== undefined) {
return cachedDefs;
}
const defs: ToolDefinition[] = [];
for (const tool of cache.values()) {
defs.push({
name: tool.name,
description: tool.description,
inputSchema: tool.inputSchema,
});
}
this.toolDefinitionsCaches.set(url, defs);
return defs;
}
/**
* 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 ToolAvailability 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';
// 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);
// 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[] = [];
// All registries without any filtering
const allRegistries: ToolRegistry[] = [
coreToolRegistry,
contextToolRegistry,
labelsToolRegistry,
mrsToolRegistry,
filesToolRegistry,
milestonesToolRegistry,
pipelinesToolRegistry,
variablesToolRegistry,
wikiToolRegistry,
workitemsToolRegistry,
snippetsToolRegistry,
webhooksToolRegistry,
integrationsToolRegistry,
releasesToolRegistry,
refsToolRegistry,
membersToolRegistry,
searchToolRegistry,
iterationsToolRegistry,
];
for (const registry of allRegistries) {
for (const [, tool] of registry) {
// Return original schema without transformation
// This preserves discriminated union structure for documentation
allTools.push(tool);
}
}
return allTools;
}
/**
* 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 cachedNames = this.toolNamesCaches.get(url);
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(url, 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;
} {
const counts = {
available: 0,
byReadOnly: 0,
byDeniedRegex: 0,
byScopes: 0,
byTier: 0,
byActionDenial: 0,
};
const counterByReason: Record<string, keyof typeof counts> = {
readOnly: 'byReadOnly',
deniedRegex: 'byDeniedRegex',
scopes: 'byScopes',
tier: 'byTier',
actionDenial: 'byActionDenial',
};
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);
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 {
// 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 unreachableMode = this.isUnreachableFor(instanceUrl);
const contextTools = unreachableMode ? this.registries.get('context') : null;
// Count total tools — in unreachable mode, only context tools are in scope
let totalTools = 0;
for (const registry of this.registries.values()) {
for (const [toolName] of registry) {
if (contextTools && !contextTools.has(toolName)) continue;
totalTools++;
}
}
// 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,
};
}
// 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 (
this.filterStatsCaches.get(url) ?? {
available: 0,
total: filteredTotal,
filteredByScopes: filteredTotal,
filteredByReadOnly: 0,
filteredByTier: 0,
filteredByDeniedRegex: 0,
filteredByActionDenial: 0,
}
);
}
const {
available: availableTools,
byReadOnly: filteredByReadOnly,
byDeniedRegex: filteredByDeniedRegex,
byScopes: filteredByScopes,
byTier: filteredByTier,
byActionDenial: filteredByActionDenial,
} = this.aggregateFilterCounters(ctx, contextTools);
const stats: FilterStats = {
available: availableTools,
total: totalTools,
filteredByScopes,
filteredByReadOnly,
filteredByTier,
filteredByDeniedRegex,
filteredByActionDenial,
};
this.filterStatsCaches.set(url, stats);
return stats;
}
}
/** 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;
}
export { RegistryManager };
|