All files / src handlers.ts

98.41% Statements 497/505
94.28% Branches 330/350
98.64% Functions 73/74
98.94% Lines 469/474

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485  18x               18x         18x 18x 18x 18x 18x 18x                   18x 18x 18x 18x               18x 18x 18x               18x 18x 18x 18x           18x                 18x 18x 18x 18x 18x 18x 18x           18x 18x                                           84x                       42x         42x 42x 1x     41x                   32x 32x 32x 32x   32x 32x 1x 1x 1x                     18x 17x                                     45x         45x 45x 3x     42x     42x 42x 28x   42x             42x                   42x 42x 42x 7x 7x         35x 35x   16x 15x   16x                                                                                       136x       130x     6x 6x   6x 1x 5x 1x   4x   6x           6x 6x                                           130x       124x   6x                 6x 6x                                   130x 130x               130x 3x                         9x   9x 9x 9x   18x 9x         9x 1x       8x               8x 1x   7x                             123x 123x 123x 123x 123x 16x 2x   16x   114x 113x 32x         111x             111x 222x 111x   1x             111x 111x 2x 2x 1x   1x         111x   10x                 7x 7x 1x 7x   1x             10x 9x       10x       10x       10x 9x 9x     10x               10x         10x       10x 10x           10x 9x   10x       18x                 333x 333x                           181x       181x                                       50x 98x 49x     18x                     154x 154x   154x 154x 11x 11x 11x     154x     533x 154x                           11x 11x 11x 11x 11x   11x         11x         4x       4x     11x   11x         45x 45x   45x 45x 45x 1x                                   43x 43x   1x 1x   42x 42x 42x 2x 2x 2x 2x 1x     1x       42x   42x 42x 1044x         1044x 1039x   42x                                         146x 146x 23x 123x 123x 123x                 123x 123x 91x 32x       32x 32x 3x   32x 32x 3x             29x     29x           28x                           174x 174x 6x 6x   6x     6x 6x                               110x 109x     108x 129x 128x 127x 1x 126x 106x 20x   129x 129x 129x 1x 128x 4x 3x 3x     108x       109x   109x 19x   109x     109x 109x   2x 2x 1x 1x                               44x 41x 41x 13x       44x   44x         18x   18x     18x 212x 212x                     18x   378x   189x       188x 184x 184x       184x 183x 183x         4x 2x   4x     2x   1x             183x       2x 2x   1x                         184x 183x 183x         183x 366x 183x   1x           1x 1x     188x     1x           188x 4x 4x 3x                     188x 5x 5x 4x 1x   3x                                 188x 43x       86x 43x 43x                     43x         86x 43x 43x         86x 43x     43x 43x 43x           43x   43x           43x             5975x     5975x     5975x         5975x 2x 2x   2x   1x   1x 1x 1x     1x 1x 1x       5973x 5973x 16855x   588x 588x     4715x   588x 16267x 217x   16050x       5973x       43x 1042x     1042x 1042x       1042x 1042x   1042x 1042x         1042x 885x 885x 885x       1042x 34x       1008x 1008x               43x           188x 44x 44x   2x 1x               188x                       298x                   149x 149x 39x 39x   148x       148x 148x   148x 148x 50x     148x           148x     148x     148x     148x 2x       296x   148x   1x                   147x 147x 147x 147x 147x       294x 147x 146x             145x 136x       136x           136x     130x               130x     123x 123x                     121x     111x 111x     111x 109x 109x 109x           111x   222x 111x 111x 111x               111x 1x     110x 2x       220x 110x 30x 30x             110x                             67x 1x         66x 65x     66x   44x       148x           148x     103x 8x               95x   45x 45x 45x     45x 45x 45x   45x 26x 26x       19x 19x               188x 154x 154x     154x     154x 154x 151x 151x   147x 146x 146x   151x 149x   11x 11x 3x 1x   3x             2x 1x   154x              
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import {
  CallToolRequestSchema,
  ErrorCode,
  ListResourcesRequestSchema,
  ListToolsRequestSchema,
  McpError,
  ReadResourceRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import {
  SETTINGS_PANEL_RESOURCE_META,
  SETTINGS_PANEL_URI,
  settingsPanelHtml,
} from './entities/context/settings-panel';
import { MCP_APP_MIME_TYPE } from './mcp-apps';
import { ConnectionManager } from './services/ConnectionManager';
import { HealthMonitor } from './services/HealthMonitor';
import { normalizeInstanceUrl } from './utils/url';
import { logInfo, logWarn, logError, logDebug } from './logger';
import {
  handleGitLabError,
  GitLabStructuredError,
  isStructuredToolError,
  createTimeoutError,
  createConnectionFailedError,
  parseGitLabApiError,
  classifyError,
  parseTimeoutError,
} from './utils/error-handler';
import { GitLabTimeoutError } from './utils/fetch';
import { GitLabApiError } from './utils/gitlab-api';
import { getRequestTracker, getConnectionTracker, getCurrentRequestId } from './logging/index';
import {
  LOG_FORMAT,
  HANDLER_TIMEOUT_MS,
  GITLAB_BASE_URL,
  GITLAB_READ_ONLY_MODE,
  GITLAB_ALLOWED_PROJECT_IDS,
  getEffectiveProjectId,
} from './config';
import { getSchemaMode } from './utils/schema-utils';
import { formatToolResult, errorToolResult } from './utils/tool-result';
import {
  APP_PANEL_SECURITY_SCHEMES,
  OAUTH_SECURITY_SCHEMES,
  resourceScopeRejection,
  toolScopeRejection,
  withReauthChallenge,
} from './oauth/tool-auth';
import type { CallToolRequest, CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { AccountUnavailableError, withChatAccount } from './accounts/chat-accounts';
import { currentMcpServer, runWithMcpServer } from './mcp-server-context';
import { currentTokenAccount } from './accounts/token-account';
import {
  getConfigurationService,
  resolveCaller,
  runWithCaller,
  type Caller,
} from './configuration';
import {
  CONFIGURATION_TOOLS,
  callRestriction,
  isExemptFromSettings,
  listedToolSchema,
  scopeLabel,
  withoutScope,
  type EffectivePolicy,
} from './configuration/policy';
import { executeScoped, parseScopedArguments } from './configuration/scoped-execution';
import { withScopePaths, withTargetPaths } from './configuration/scope-ids';
import { operatorProjectRejection, withOperatorProjects } from './configuration/operator-projects';
import { assertOperatorOwnership } from './configuration/operator-ownership';
import { extractProjectsFromArgs } from './profiles/scope-enforcer';
import { withDefaultProject } from './configuration/default-project';
import {
  withNamespaceCapabilities,
  namespaceTargetsForScope,
  namespaceTargetsForArgs,
  needsNamespaceTier,
} from './configuration/namespace-capabilities';
import { canResolveNamespaceTier } from './services/NamespaceTierDetector';
import { hasNamespaceSubscriptions } from './services/namespace-tier-context';
 
interface JsonSchemaProperty {
  type?: string;
  $ref?: string;
  properties?: Record<string, JsonSchemaProperty>;
  items?: JsonSchemaProperty;
  enum?: unknown[];
  oneOf?: JsonSchemaProperty[];
  anyOf?: JsonSchemaProperty[];
  [key: string]: unknown;
}
 
type JsonSchema = JsonSchemaProperty & {
  $schema?: string;
  properties?: Record<string, JsonSchemaProperty>;
};
 
/**
 * Type guard for objects with an action property
 */
function hasAction(value: unknown): value is { action: string } {
  return (
    typeof value === 'object' &&
    value !== null &&
    'action' in value &&
    typeof value.action === 'string'
  );
}
 
/**
 * Extract action from error or its cause chain
 */
function extractActionFromError(error: unknown): string | undefined {
  Iif (hasAction(error)) {
    return error.action;
  }
 
  // Check error cause (for wrapped errors)
  const cause = (error as Error & { cause?: unknown }).cause;
  if (hasAction(cause)) {
    return cause.action;
  }
 
  return undefined;
}
 
/** Record tool/error in condensed-mode access logs and connection stats.
 *  Used by early-return paths (disconnected, bootstrap failure, timeout). */
function recordEarlyReturnError(
  toolName: string,
  action: string | undefined,
  errorMessage: string,
): void {
  const requestTracker = getRequestTracker();
  Eif (LOG_FORMAT === 'condensed') {
    requestTracker.setToolForCurrentRequest(toolName, action);
    requestTracker.setErrorForCurrentRequest(errorMessage);
  }
  const currentRequestId = getCurrentRequestId();
  if (currentRequestId) {
    const stack = requestTracker.getStack(currentRequestId);
    Eif (stack?.sessionId) {
      getConnectionTracker().recordError(stack.sessionId, errorMessage);
    }
  }
}
 
/**
 * Check if a tool operation is idempotent (safe to retry).
 * browse_*, list_*, get_*, download_* are read-only.
 * Mixed command tools, including session mutations, are conservative.
 */
function isIdempotentOperation(toolName: string, declared?: boolean): boolean {
  if (declared !== undefined) return declared;
  return (
    toolName.startsWith('browse_') ||
    toolName.startsWith('list_') ||
    toolName.startsWith('get_') ||
    toolName.startsWith('download_')
  );
}
 
/**
 * Convert an error to a structured GitLab error response
 * Extracts tool name and action from context, parses API errors
 */
function toStructuredError(
  error: unknown,
  toolName: string,
  toolArgs?: Record<string, unknown>,
  declaredIdempotent?: boolean,
): GitLabStructuredError | null {
  // If already a structured error, return it
  Iif (isStructuredToolError(error)) {
    return error.structuredError;
  }
 
  // Check if the error cause is a structured error (for wrapped errors)
  const cause = (error as Error & { cause?: unknown }).cause;
  if (isStructuredToolError(cause)) {
    return cause.structuredError;
  }
 
  Iif (!(error instanceof Error)) return null;
 
  // Extract action early - needed for both timeout and API errors
  let action = extractActionFromError(error);
  if (!action && toolArgs && typeof toolArgs.action === 'string') {
    action = toolArgs.action;
  }
  action ??= 'unknown';
 
  // Check for timeout error first (before parseGitLabApiError).
  // Primary: instanceof for type safety in production.
  // Fallback: duck-typing by name+property for cross-module-graph cases.
  // Last resort: parse message string (covers handler-timeout wrapper case where
  // the original GitLabTimeoutError message is embedded in a generic Error).
  Iif (
    error instanceof GitLabTimeoutError ||
    (error instanceof Error &&
      error.name === 'GitLabTimeoutError' &&
      'timeoutMs' in error &&
      typeof (error as GitLabTimeoutError).timeoutMs === 'number')
  ) {
    const retryable = isIdempotentOperation(toolName, declaredIdempotent);
    return createTimeoutError(toolName, action, (error as GitLabTimeoutError).timeoutMs, retryable);
  }
  Eif (error instanceof Error) {
    const timeoutMs = parseTimeoutError(error.message);
    if (timeoutMs !== null) {
      const retryable = isIdempotentOperation(toolName, declaredIdempotent);
      return createTimeoutError(toolName, action, timeoutMs, retryable);
    }
  }
 
  // Preserve the existing diagnostic format; typed REST metadata never comes from text.
  const parsed = parseGitLabApiError(error.message);
  if (!parsed) return null;
  let apiError: GitLabApiError | undefined;
  if (error instanceof GitLabApiError) apiError = error;
  else if (cause instanceof GitLabApiError) apiError = cause;
 
  return handleGitLabError(
    {
      status: parsed.status,
      message: parsed.message,
      ...(apiError && { retryAfterSeconds: apiError.retryAfterSeconds }),
    },
    toolName,
    action,
    toolArgs,
  );
}
 
/** Tracks connection bootstrap progress; shared with the handler-level timeout path. */
interface BootstrapState {
  started: boolean;
  complete: boolean;
}
 
/** Dependencies and per-call values passed to ensureBootstrapped. */
interface BootstrapContext {
  toolName: string;
  toolArguments: Record<string, unknown> | undefined;
  effectiveInstanceUrl: string;
  oauthMode: boolean;
  requestScopes?: readonly string[];
  connectionManager: ConnectionManager;
  healthMonitor: HealthMonitor;
  isTimedOut: () => boolean;
  bootstrapState: BootstrapState;
}
 
/**
 * Return a CONNECTION_FAILED response if the target instance is unreachable for
 * non-context tools, or null to proceed normally.
 *
 * Configuration tools always pass through: they work on local state and are how the
 * caller finds out about, and recovers from, the disconnected state.
 */
function checkUnreachableInstance(
  toolName: string,
  toolArguments: Record<string, unknown> | undefined,
  effectiveInstanceUrl: string,
  healthMonitor: HealthMonitor,
): CallToolResult | null {
  if (
    healthMonitor.isInstanceReachable(effectiveInstanceUrl) ||
    CONFIGURATION_TOOLS.has(toolName)
  ) {
    return null;
  }
  const action =
    toolArguments && typeof toolArguments.action === 'string' ? toolArguments.action : 'unknown';
  const rawState = healthMonitor.getState(effectiveInstanceUrl);
  let connectionState: 'connecting' | 'disconnected' | 'failed';
  if (rawState === 'failed') {
    connectionState = 'failed';
  } else if (rawState === 'connecting') {
    connectionState = 'connecting';
  } else {
    connectionState = 'disconnected';
  }
  const connError = createConnectionFailedError(
    toolName,
    action,
    effectiveInstanceUrl,
    connectionState,
  );
  recordEarlyReturnError(toolName, action, connError.message);
  return errorToolResult(connError);
}
 
/**
 * Fast-path for configuration tools when the instance is unreachable: bypass connection
 * bootstrap and health reporting. Returns a tool response if handled, or null to
 * fall through to the normal bootstrap path.
 *
 * Bypasses bootstrap intentionally — context tools mostly operate on local state
 * (cached scopes, config, instance registry). Some of them read GitLab too (check_connection,
 * find_scope_targets, scope checks), and a caller runs them to check or recover the
 * connection; their own success says nothing about GitLab, so instead of reporting it the
 * monitor is asked to probe GitLab again, which lets other tools recover at once.
 */
async function tryManageContextFastPath(
  toolName: string,
  toolArguments: Record<string, unknown> | undefined,
  effectiveInstanceUrl: string,
  healthMonitor: HealthMonitor,
  sessionId: string | undefined,
  requestScopes: readonly string[] | undefined,
): Promise<CallToolResult | null> {
  if (
    !CONFIGURATION_TOOLS.has(toolName) ||
    healthMonitor.isInstanceReachable(effectiveInstanceUrl)
  ) {
    return null;
  }
  const result = await executeWithoutBootstrap(
    toolName,
    toolArguments,
    effectiveInstanceUrl,
    requestScopes,
  );
  // Not rate-limited: only a user's settings call while GitLab is unreachable asks for this
  // probe, the monitor drops it while one is running, and a cooldown would keep the other
  // tools down after GitLab answers again, which is what the probe is for.
  if (result) healthMonitor.forceReconnect(effectiveInstanceUrl);
  return result;
}
 
/**
 * Calls that run without bootstrapping the instance: configuration tools while it is
 * unreachable, and the account actions always. Listing, switching, linking and unlinking
 * accounts read the session store and the instance configuration, never this instance, so a
 * chat whose instance fails to start can still move to an account that works. Returns null
 * to fall through to the bootstrap path.
 */
async function tryWithoutBootstrap(
  request: CallToolRequest,
  toolArguments: Record<string, unknown> | undefined,
  effectiveInstanceUrl: string,
  healthMonitor: HealthMonitor,
  sessionId: string | undefined,
  requestScopes: readonly string[] | undefined,
): Promise<CallToolResult | null> {
  const toolName = request.params.name;
  const fastPath = await tryManageContextFastPath(
    toolName,
    toolArguments,
    effectiveInstanceUrl,
    healthMonitor,
    sessionId,
    requestScopes,
  );
  if (fastPath || !managesAccounts(request)) return fastPath;
  return executeWithoutBootstrap(toolName, toolArguments, effectiveInstanceUrl, requestScopes);
}
 
/**
 * Run a tool without bootstrapping its instance. Returns null when the tool is not in the
 * instance's cache, so the caller falls through to the bootstrap path.
 */
async function executeWithoutBootstrap(
  toolName: string,
  toolArguments: Record<string, unknown> | undefined,
  effectiveInstanceUrl: string,
  requestScopes: readonly string[] | undefined,
): Promise<CallToolResult | null> {
  Eif (LOG_FORMAT === 'condensed') {
    const action =
      toolArguments && typeof toolArguments.action === 'string' ? toolArguments.action : undefined;
    const requestTracker = getRequestTracker();
    requestTracker.setToolForCurrentRequest(toolName, action);
  }
  const { RegistryManager } = await import('./registry-manager');
  const registryManager = RegistryManager.getInstance();
  // hasToolHandler + executeTool are not a single atomic operation — a concurrent
  // refreshCache() could swap the lookup cache between the two calls. In practice
  // this is benign: executeTool() falls through with undefined and we re-enter the
  // bootstrap path below. A full atomic getTool() refactor is tracked separately.
  if (!registryManager.hasToolHandler(toolName, effectiveInstanceUrl)) {
    return null; // tool not yet cached — fall through to bootstrap
  }
  // The request's grants apply here too: a token without the tool's scopes is refused
  // exactly as on the connected path, whatever GitLab's reachability.
  const result = await registryManager.executeTool(
    toolName,
    toolArguments,
    effectiveInstanceUrl,
    requestScopes,
  );
  // If executeTool returns undefined (TOCTOU: cache was refreshed between hasToolHandler and
  // executeTool), fall through to the bootstrap path instead of returning {text: "undefined"}.
  if (result === undefined) {
    return null;
  }
  return formatToolResult(
    result,
    registryManager.getTool(toolName, effectiveInstanceUrl, requestScopes),
  );
}
 
/**
 * Initialize the connection, verify the client, and rebuild the per-URL tool cache.
 *
 * Mutates bootstrapState to track progress for the handler-level timeout path.
 * Returns a CONNECTION_FAILED response when bootstrap fails (connection, client, or
 * introspection step), or undefined on success. All errors are handled internally
 * and surfaced as a CONNECTION_FAILED payload — none are rethrown to the caller.
 */
async function ensureBootstrapped(ctx: BootstrapContext): Promise<CallToolResult | undefined> {
  const { effectiveInstanceUrl, oauthMode, requestScopes, connectionManager, bootstrapState } = ctx;
  bootstrapState.started = true;
  try {
    const firstInitialization = !connectionManager.isConnected(effectiveInstanceUrl);
    if (firstInitialization) {
      if (LOG_FORMAT === 'verbose') {
        logInfo('Connection not initialized, attempting to initialize...');
      }
      await connectionManager.initialize(effectiveInstanceUrl);
    }
    connectionManager.getClient(effectiveInstanceUrl);
    if (oauthMode) {
      await connectionManager.ensureIntrospected(effectiveInstanceUrl, requestScopes);
    }
    // Mark bootstrap complete BEFORE cache rebuild — refreshCache is local
    // bookkeeping, not a connectivity step. If it fails, the tool call should
    // still proceed (not return CONNECTION_FAILED for a successful connection).
    bootstrapState.complete = true;
    // Rebuild per-URL registry cache AFTER full bootstrap (initialize + introspection)
    // so tier/version/widget availability are all populated.
    // Cache is keyed by normalized URL — concurrent multi-instance requests
    // each get their own cache entry and cannot interfere (#379).
    // Isolated try/catch: cache rebuild is best-effort; a failure must NOT abort
    // the tool call — the connection is already established at this point.
    try {
      const { RegistryManager } = await import('./registry-manager');
      RegistryManager.getInstance().refreshCache(effectiveInstanceUrl);
    } catch (cacheError) {
      logWarn('Failed to refresh registry cache after bootstrap', {
        instanceUrl: effectiveInstanceUrl,
        err: cacheError as Error,
      });
    }
    // A list sent before the instance was initialized (a chat that just switched to it,
    // say) could not be filtered by its version, tier and token scopes: clients list again.
    if (firstInitialization) announceToolListChange(effectiveInstanceUrl);
    if (LOG_FORMAT === 'verbose') {
      try {
        const instanceInfo = connectionManager.getInstanceInfo(effectiveInstanceUrl);
        logInfo(`Connection verified: ${instanceInfo.version} ${instanceInfo.tier}`);
      } catch {
        logDebug('Connection verified but instance info not yet available', {
          instanceUrl: effectiveInstanceUrl,
        });
      }
    }
    return undefined;
  } catch (initError) {
    return formatBootstrapFailure(ctx, initError);
  }
}
 
/**
 * Tell the sessions on `instanceUrl` and the calling chat (a sessionless one, or one on the
 * same instance with another account) that their tool list changed; best effort.
 */
function announceToolListChange(instanceUrl: string): void {
  void import('./session-manager')
    .then(({ getSessionManager }) => getSessionManager().broadcastToolsListChanged(instanceUrl))
    .catch((error: unknown) => logDebug('Could not announce the tool list', { err: error }));
  void currentMcpServer()
    ?.sendToolListChanged()
    .catch((error: unknown) => logDebug('Could not announce the tool list', { err: error }));
}
 
function bootstrapFailureState(
  monitorState: string,
  category: ReturnType<typeof classifyError>,
): 'connecting' | 'disconnected' | 'failed' {
  if (monitorState === 'connecting' || monitorState === 'failed') return monitorState;
  return category === 'auth' || category === 'permanent' ? 'failed' : 'disconnected';
}
 
function formatBootstrapFailure(ctx: BootstrapContext, initError: unknown): CallToolResult {
  const { toolName, toolArguments, effectiveInstanceUrl, healthMonitor, isTimedOut } = ctx;
  // Bootstrap has not completed here: refreshCache is isolated above,
  // so the only way to reach this catch is initialize()/getClient()/ensureIntrospected()
  // failing before bootstrapState.complete was set.
  const errorCategory = initError instanceof Error ? classifyError(initError) : 'permanent';
  // Report bootstrap failure to HealthMonitor. When the handler has already
  // timed out, we still forward auth/permanent errors so the instance
  // converges to `failed` instead of staying in `reconnecting` indefinitely.
  if (initError instanceof Error) {
    Eif (!isTimedOut() || errorCategory === 'auth' || errorCategory === 'permanent') {
      healthMonitor.reportError(effectiveInstanceUrl, initError);
    }
  }
  logError(
    `Connection initialization failed: ${initError instanceof Error ? initError.message : String(initError)}`,
    {
      instanceUrl: effectiveInstanceUrl,
      err: initError instanceof Error ? initError : new Error(String(initError)),
    },
  );
  const action =
    toolArguments && typeof toolArguments.action === 'string' ? toolArguments.action : 'unknown';
  // Use error classification together with HealthMonitor state to determine
  // the derived connection state. For untracked URLs, getState() falls back
  // to 'disconnected', so we must not rely on that alone — otherwise
  // permanent/auth failures would incorrectly appear retriable.
  const monitorState = healthMonitor.getState(effectiveInstanceUrl);
  // Prefer explicit monitor states when available; otherwise derive from the
  // error category: auth/permanent → failed (no auto-retry),
  // transient/other → disconnected (retriable)
  const derivedState = bootstrapFailureState(monitorState, errorCategory);
  const connError = createConnectionFailedError(
    toolName,
    action,
    effectiveInstanceUrl,
    derivedState,
  );
  if (!isTimedOut()) {
    recordEarlyReturnError(toolName, action, connError.message);
  }
  return withReauthChallenge(errorToolResult(connError), initError);
}
 
/** manage_context actions that manage the connection's accounts. */
const ACCOUNT_ACTIONS: ReadonlySet<string> = new Set([
  'list_accounts',
  'switch_account',
  'link_account',
  'unlink_account',
]);
 
/** Whether a call lists, switches, links or unlinks the connection's accounts. */
function managesAccounts(request: CallToolRequest): boolean {
  const action = request.params.arguments?.action;
  return (
    request.params.name === 'manage_context' &&
    typeof action === 'string' &&
    ACCOUNT_ACTIONS.has(action)
  );
}
 
/**
 * The instance a request works with, normalized: the OAuth token's (the configured one
 * without a request context), else the instance the static token works with now.
 */
function activeInstanceUrl(oauthEnabled: boolean, oauthContextUrl: string | undefined): string {
  // A static-token chat works with the server's own instance, or the configured one it
  // switched to; another chat's switch never moves it.
  const raw = oauthEnabled
    ? (oauthContextUrl ?? GITLAB_BASE_URL)
    : (currentTokenAccount()?.instanceUrl ?? GITLAB_BASE_URL);
  // Normalized so CONNECTION_FAILED instance_url and HealthMonitor keys are consistent.
  return normalizeInstanceUrl(raw);
}
 
/**
 * Keep the session's instance URL in sync so ListTools requests reflect the instance its
 * calls go to, and no other: in OAuth mode that is the token's instance, so context changes
 * (switch_preset, reset) need no re-pin of their own. In OAuth mode only a real context URL
 * is pinned; the GITLAB_BASE_URL fallback of a contextless call (health checks, non-OAuth
 * transport) must not overwrite a session pinned to a specific instance. In static-token
 * mode the active instance is always tracked.
 *
 * Account actions do not pin: they run as the connection's own account whichever account
 * the chat switched to, and switch_account pins the instance it moves to itself.
 */
async function pinSessionInstance(
  sessionId: string,
  oauthEnabled: boolean,
  oauthContextUrl: string | undefined,
  instanceUrl: string,
): Promise<void> {
  if (oauthEnabled && oauthContextUrl === undefined) return;
  const { getSessionManager } = await import('./session-manager');
  getSessionManager().setSessionInstanceUrl(sessionId, instanceUrl);
}
 
const HANDLER_TIMEOUT = Symbol('handler_timeout');
 
/** The time a call has from its arrival; resolving its account and running it share it. */
interface CallDeadline {
  signal: AbortSignal;
  expired: Promise<typeof HANDLER_TIMEOUT>;
  isExpired: () => boolean;
  clear: () => void;
}
 
function startCallDeadline(): CallDeadline {
  const cancellation = new AbortController();
  let expired = false;
  let timer: ReturnType<typeof setTimeout> | undefined;
  const promise = new Promise<typeof HANDLER_TIMEOUT>((resolve) => {
    timer = setTimeout(() => {
      expired = true;
      resolve(HANDLER_TIMEOUT);
      cancellation.abort(new GitLabTimeoutError('body', HANDLER_TIMEOUT_MS));
    }, HANDLER_TIMEOUT_MS);
  });
  return {
    signal: cancellation.signal,
    expired: promise,
    isExpired: () => expired,
    clear: () => clearTimeout(timer),
  };
}
 
/**
 * The response to a call whose handler ran out of time; the handler may still be running.
 * A bootstrap it left unfinished is reported to the health monitor.
 */
function handlerTimeoutResult(
  request: CallToolRequest,
  declaredIdempotent: boolean | undefined,
  bootstrapState: BootstrapState,
  requestInstanceUrl: string,
): CallToolResult {
  const toolName = request.params.name;
  const requested = request.params.arguments?.action;
  const action = typeof requested === 'string' ? requested : 'unknown';
  const retryable = isIdempotentOperation(toolName, declaredIdempotent);
  const timeoutError = createTimeoutError(toolName, action, HANDLER_TIMEOUT_MS, retryable);
 
  logError(`Handler timeout: tool '${toolName}' timed out after ${HANDLER_TIMEOUT_MS}ms`);
 
  // Only report to health monitor and clear inflight if bootstrap was
  // actually attempted (not for disconnected manage_context bypass which
  // does no GitLab I/O and shouldn't affect connection health).
  if (bootstrapState.started && !bootstrapState.complete) {
    // Use "timed out" so classifyError() reliably treats this as transient
    // and triggers disconnected → auto-reconnect. Use a plain Error (not
    // InitializationTimeoutError) because this is a handler-level timeout,
    // not the startup init timeout from HealthMonitor.performConnect.
    HealthMonitor.getInstance().reportError(
      requestInstanceUrl,
      new Error(`Handler timed out after ${HANDLER_TIMEOUT_MS}ms — bootstrap did not complete`),
    );
    ConnectionManager.getInstance().clearInflight(requestInstanceUrl);
  }
 
  recordEarlyReturnError(toolName, action, timeoutError.message);
 
  return errorToolResult(timeoutError);
}
 
/** Record a failed call for the access log and on its connection's stats. */
function recordToolError(errMsg: string): void {
  const reqTracker = getRequestTracker();
  reqTracker.setErrorForCurrentRequest(errMsg);
 
  const curRequestId = getCurrentRequestId();
  const sessionId = curRequestId ? reqTracker.getStack(curRequestId)?.sessionId : undefined;
  if (sessionId) {
    getConnectionTracker().recordError(sessionId, errMsg);
  }
}
 
/**
 * The tool list narrowed by the caller's settings: restricted tools and the actions the
 * preset denies are left out. When the settings cannot be read the list stays as the
 * registry built it: listing is only visibility, and every call is still checked (and
 * refused while the settings cannot be read).
 */
async function withoutRestrictedTools<
  T extends { name: string; inputSchema: Record<string, unknown> },
>(
  tools: () => T[],
  caller: Caller,
  registryManager: import('./registry-manager').RegistryManager,
): Promise<T[]> {
  let policy: EffectivePolicy;
  try {
    policy = (await getConfigurationService().resolve(caller)).policy;
  } catch (error: unknown) {
    logWarn('Could not read the caller settings for the tool list', { err: error as Error });
    return tools();
  }
  const catalog = await runWithCaller(caller, async () => {
    let targets = namespaceTargetsForScope(policy.scope);
    if (hasNamespaceSubscriptions(caller.instanceUrl) && GITLAB_ALLOWED_PROJECT_IDS.length > 0) {
      targets = [];
      Eif (canResolveNamespaceTier(caller.instanceUrl)) {
        try {
          const operatorPolicy = await withOperatorProjects(policy);
          targets = namespaceTargetsForScope(operatorPolicy.scope);
        } catch {
          // Billing discovery is optional; execution still verifies operator restrictions.
          logWarn('Could not resolve operator projects for namespace discovery');
        }
      }
    }
    return withNamespaceCapabilities(caller.instanceUrl, targets, true, tools);
  });
  const listed: T[] = [];
  for (const tool of catalog) {
    const inputSchema = listedToolSchema(
      policy,
      registryManager.getToolFacts(tool.name),
      tool.inputSchema,
    );
    if (inputSchema)
      listed.push(inputSchema === tool.inputSchema ? tool : { ...tool, inputSchema });
  }
  return listed;
}
 
/**
 * A refusal for a call the caller's settings do not allow, or null when it may run. Tool,
 * group, read-only and action limits come first: they need nothing from GitLab, so a call
 * they refuse reaches nothing. Then the scope, which compares paths: numeric ids, the call's
 * and the scope's own, are checked as the paths they stand for. The returned policy is the
 * one the call runs under.
 */
async function prepareScopedCall(
  toolName: string,
  args: Record<string, unknown>,
  configured: EffectivePolicy,
  registryManager: import('./registry-manager').RegistryManager,
  expired: () => boolean,
): Promise<{
  rejection: CallToolResult | null;
  args: Record<string, unknown>;
  policy: EffectivePolicy;
}> {
  const unscoped = settingsRejection(toolName, args, withoutScope(configured), registryManager);
  if (unscoped || isExemptFromSettings(toolName))
    return { rejection: unscoped, args, policy: configured };
  const action = typeof args.action === 'string' ? args.action : undefined;
  const defaultProject = getEffectiveProjectId(undefined);
  const defaults = defaultProject
    ? await withDefaultProject(
        toolName,
        args,
        registryManager.getDeclaredArguments(toolName, action),
        defaultProject,
        expired,
      )
    : { args, read: undefined };
  args = defaults.args;
  if (!configured.scopeEnforcer && GITLAB_ALLOWED_PROJECT_IDS.length === 0)
    return { rejection: null, args, policy: configured };
  const selected = parseScopedArguments(toolName, args);
  // The tool's parse keeps only the selected action's arguments, so only those are held to
  // the scope.
  const declared =
    selected === args ? registryManager.getDeclaredArguments(toolName, action) : undefined;
  const own = declared
    ? Object.fromEntries(Object.entries(selected).filter(([name]) => declared.has(name)))
    : selected;
  const operatorRejection = operatorProjectRejection(own);
  if (operatorRejection) {
    return {
      rejection: errorToolResult({ error: operatorRejection }),
      args: selected,
      policy: configured,
    };
  }
  const policy =
    GITLAB_ALLOWED_PROJECT_IDS.length > 0
      ? await withOperatorProjects(configured, defaults.read, expired, extractProjectsFromArgs(own))
      : await withScopePaths(configured, defaults.read);
  const rejection = settingsRejection(
    toolName,
    await withTargetPaths(own, defaults.read, policy.scopeEnforcer),
    policy,
    registryManager,
  );
  return {
    rejection,
    args: selected,
    policy,
  };
}
 
/** A refusal for a call the given policy does not allow, or null when it may run. */
function settingsRejection(
  toolName: string,
  args: Record<string, unknown>,
  policy: EffectivePolicy,
  registryManager: import('./registry-manager').RegistryManager,
): CallToolResult | null {
  const reason = callRestriction(policy, registryManager.getToolFacts(toolName), args);
  if (reason === null) return null;
  const action = typeof args.action === 'string' ? args.action : undefined;
  const call = action ? `${toolName} ${action}` : toolName;
  const message =
    `'${call}' is not allowed by the current settings: ` +
    `${reason}. The account settings are changed with update_settings, this session's ` +
    'with manage_context.';
  recordEarlyReturnError(toolName, action, message);
  return errorToolResult({ error: message });
}
 
/**
 * Runs the tool through the registry (per-URL cache). A listing that names no target
 * reads the working scope instead of everything the account sees.
 */
async function executeInScope(
  registryManager: import('./registry-manager').RegistryManager,
  toolName: string,
  requested: Record<string, unknown>,
  policy: EffectivePolicy,
  instanceUrl: string,
  requestScopes: readonly string[] | undefined,
  expired: () => boolean,
): Promise<unknown> {
  await assertOperatorOwnership(toolName, requested, policy, expired);
  if (expired()) throw new Error('Tool call expired before execution');
  // executeScoped wraps this runner so every call it makes in place of the requested one is
  // held to the preset's denied actions; the operator's are checked by each tool itself.
  const run = (tool: string, toolArgs: Record<string, unknown>): Promise<unknown> => {
    const dispatch = (validated: Record<string, unknown>): Promise<unknown> => {
      if (expired()) return Promise.reject(new Error('Tool call expired before execution'));
      if (tool === 'browse_duo_sessions' || tool === 'manage_duo_session')
        return registryManager.executeTool(tool, validated, instanceUrl, requestScopes, policy);
      if (requestScopes === undefined)
        return registryManager.executeTool(tool, validated, instanceUrl);
      return registryManager.executeTool(tool, validated, instanceUrl, requestScopes);
    };
    const definition = registryManager.getTool(tool, instanceUrl, requestScopes);
    const action = toolArgs.action;
    if (typeof action === 'string' && definition?.unavailableActions?.has(action.toLowerCase()))
      return dispatch(toolArgs);
    if (!needsNamespaceTier(definition?.requirements)) return dispatch(toolArgs);
    const validated = parseScopedArguments(tool, toolArgs);
    return withNamespaceCapabilities(instanceUrl, namespaceTargetsForArgs(validated), false, () =>
      dispatch(validated),
    );
  };
  return executeScoped(run, toolName, requested, policy, true);
}
 
function recordCallContext(scopePath: string | undefined, readOnly: boolean): void {
  const requestTracker = getRequestTracker();
  // Capture current context and read-only state for access logging
  if (scopePath) {
    requestTracker.setContextForCurrentRequest(scopePath);
  }
  requestTracker.setReadOnlyForCurrentRequest(readOnly);
 
  // Increment tool count for connection tracking
  const currentRequestId = getCurrentRequestId();
  if (currentRequestId) {
    // Get session ID from the request stack to update connection stats
    const stack = requestTracker.getStack(currentRequestId);
    if (stack?.sessionId) {
      const connectionTracker = getConnectionTracker();
      connectionTracker.incrementTools(stack.sessionId);
    }
  }
}
 
function throwDispatchError(
  error: unknown,
  toolName: string,
  instanceUrl: string,
  healthMonitor: HealthMonitor,
  timedOut: boolean,
): never {
  // Only report connectivity/auth errors to HealthMonitor — not request-level
  // 4xx (e.g. 404 "project not found") which don't indicate connection problems.
  // classifyError returns 'permanent' for 4xx like 400/403/404, 'transient' for network issues,
  // and 'auth' for authentication errors like 401; only 'transient' and 'auth' are reported here.
  if (!timedOut && error instanceof Error) {
    const category = classifyError(error);
    if (category === 'transient' || category === 'auth') {
      healthMonitor.reportError(instanceUrl, error);
    }
  }
 
  const errorMessage = error instanceof Error ? error.message : String(error);
  // Preserve original error as cause to allow action extraction and structured error detection
  throw new Error(`Failed to execute tool '${toolName}': ${errorMessage}`, { cause: error });
}
 
/** One-shot startup promise: health monitor init + registry refresh.
 *  Concurrent setupHandlers() calls await the same promise instead of racing. */
let healthMonitorStartup: Promise<void> | null = null;
/** One-shot guard: state change callback is registered exactly once */
let stateChangeRegistered = false;
 
/** Reset guard for testing */
export function resetHandlersState(): void {
  healthMonitorStartup = null;
  stateChangeRegistered = false;
}
 
/**
 * Register all MCP request handlers on a Server instance.
 *
 * Called once per session by SessionManager. Handlers are idempotent across
 * sessions — the same logic is registered on each per-session Server instance.
 * One-shot initialisation guards (HealthMonitor startup, state-change callback)
 * are protected by module-level flags so they run exactly once across all sessions.
 */
export async function setupHandlers(server: Server): Promise<void> {
  // Check if authentication is configured before trying to initialize connection
  const { isAuthenticationConfigured } = await import('./oauth/index');
 
  if (isAuthenticationConfigured()) {
    // Initialize health monitor ONCE (setupHandlers is called per session,
    // but the broadcast callback affects all sessions — avoid duplicate registrations).
    // Use a shared promise so concurrent sessions await the same work.
    healthMonitorStartup ??= (async () => {
      try {
        const healthMonitor = HealthMonitor.getInstance();
 
        // Register state change callback exactly once — guard prevents duplicates
        // if healthMonitorStartup resets to null on failure and retries.
        if (!stateChangeRegistered) {
          stateChangeRegistered = true;
          const broadcastToolsListChangedForStateChange = async (
            instanceUrl: string,
            from: string,
            to: string,
          ): Promise<void> => {
            const { RegistryManager } = await import('./registry-manager');
            RegistryManager.getInstance().refreshCache(instanceUrl);
 
            const { getSessionManager } = await import('./session-manager');
            // Pass instanceUrl so only sessions targeting the changed instance are notified.
            // Sessions on other instances have no tool list changes from this state transition.
            await getSessionManager().broadcastToolsListChanged(instanceUrl);
 
            logInfo('Tool list updated after connection state change', {
              instanceUrl,
              from,
              to,
            });
          };
 
          healthMonitor.onStateChange((instanceUrl, from, to) => {
            // Broadcast on any state transition that could change the tool list:
            // disconnected↔connected changes available registries, and degraded↔healthy
            // can enable/disable version-gated tools (version goes from 'unknown' to real).
            Eif (from !== to) {
              broadcastToolsListChangedForStateChange(instanceUrl, from, to).catch(
                (error: unknown) => {
                  logWarn('Failed to broadcast tools/list_changed after state change', {
                    instanceUrl,
                    err: error as Error,
                  });
                },
              );
            }
          });
        }
 
        // Initializes with default GITLAB_BASE_URL only. OAuth multi-instance
        // URLs are NOT auto-tracked — reportSuccess/reportError are no-ops for
        // untracked URLs. Untracked URLs pass isInstanceReachable() as reachable.
        await healthMonitor.initialize();
        const state = healthMonitor.getState();
        logInfo('Connection health monitor initialized', { state });
 
        // Rebuild registry cache after initialization — applies tier/version info
        // when healthy/degraded, or applies disconnected-mode tool filtering otherwise.
        // Best-effort: a cache rebuild failure should not block handler installation.
        try {
          const { RegistryManager } = await import('./registry-manager');
          RegistryManager.getInstance().refreshCache();
        } catch (cacheError) {
          logWarn('Failed to refresh registry cache during handler setup', {
            err: cacheError as Error,
          });
        }
      } catch (error) {
        // Reset so the next session retries instead of re-awaiting a rejected promise
        healthMonitorStartup = null;
        throw error;
      }
    })();
    await healthMonitorStartup;
  } else {
    // No authentication configured - server will respond to tools/list but tool calls will fail
    logInfo('Skipping connection initialization - no authentication configured');
  }
 
  // The settings panel is the server's one resource: an MCP App document. It holds no
  // account data; everything it shows comes from tool calls made with the caller's own
  // authorization.
  server.setRequestHandler(ListResourcesRequestSchema, () => {
    const rejection = resourceScopeRejection();
    if (rejection) throw rejection;
    return {
      resources: [
        {
          uri: SETTINGS_PANEL_URI,
          name: 'GitLab connection panel',
          mimeType: MCP_APP_MIME_TYPE,
          _meta: SETTINGS_PANEL_RESOURCE_META,
        },
      ],
    };
  });
  server.setRequestHandler(ReadResourceRequestSchema, (request) => {
    const rejection = resourceScopeRejection();
    if (rejection) throw rejection;
    if (request.params.uri !== SETTINGS_PANEL_URI) {
      throw new McpError(ErrorCode.InvalidParams, `Unknown resource: ${request.params.uri}`);
    }
    return {
      contents: [
        {
          uri: SETTINGS_PANEL_URI,
          mimeType: MCP_APP_MIME_TYPE,
          text: settingsPanelHtml(),
          _meta: SETTINGS_PANEL_RESOURCE_META,
        },
      ],
    };
  });
 
  // List tools handler
  // Uses per-session instance URL tracking so each session receives the tool list
  // filtered for its target GitLab instance (#398). The sessionId from RequestHandlerExtra
  // resolves to the instance URL stored in SessionManager (set on session creation and
  // kept in sync by the CallToolRequestSchema handler on every tool call).
  const listTools = async (extra: { sessionId?: string } | undefined) => {
    logInfo('ListToolsRequest received');
 
    // Resolve the instance URL for this session so the tool list reflects the
    // correct tier/version/scope restrictions for the session's target instance.
    const { getSessionManager: getSessionMgr } = await import('./session-manager');
    const sessionMgr = getSessionMgr();
    const listToolsSessionId = extra?.sessionId;
    // SessionManager always initialises instanceUrl on createSession(), so undefined here
    // means the sessionId is unknown/expired (or absent). Pass it through so
    // getAllToolDefinitions can resolve via its built-in chain: OAuth request context →
    // current instance URL → GITLAB_BASE_URL. Substituting GITLAB_BASE_URL explicitly
    // would short-circuit that chain and return the wrong tool list for OAuth requests
    // with a real context URL or after an instance switch (#398).
    //
    // HTTP OAuth requests carry their own token context, including tools/list.
    // Static-token requests use the tracked session URL after an instance switch.
    const sessionInstanceUrl =
      listToolsSessionId !== undefined
        ? sessionMgr.getSessionInstanceUrl(listToolsSessionId)
        : undefined;
 
    // Get tools from registry manager (already filtered by tier/version/scopes)
    const { RegistryManager } = await import('./registry-manager');
    const registryManager = RegistryManager.getInstance();
    const mode = getSchemaMode(server.getClientVersion()?.name);
    const {
      getTokenContext: getCatalogContext,
      isOAuthEnabled: isCatalogOAuth,
      getGitLabApiUrlFromContext: getCatalogUrl,
    } = await import('./oauth/index');
    const scopes = getCatalogContext()?.gitlabScopes;
    // OAuth deployments declare the token every tool needs; static-token mode keeps
    // the descriptors as before.
    const securitySchemes = isCatalogOAuth() ? OAUTH_SECURITY_SCHEMES : undefined;
    const catalog = () =>
      scopes === undefined
        ? registryManager.getAllToolDefinitions(sessionInstanceUrl, mode)
        : registryManager.getAllToolDefinitions(sessionInstanceUrl, mode, scopes);
    // A sessionless client (stdio) is listed with the settings of the instance its calls run
    // against, which follows the account the chat switched to.
    const callerInstanceUrl =
      sessionInstanceUrl ??
      activeInstanceUrl(isCatalogOAuth(), isCatalogOAuth() ? getCatalogUrl() : undefined);
    const tools = await withoutRestrictedTools(
      catalog,
      resolveCaller(listToolsSessionId, callerInstanceUrl),
      registryManager,
    );
 
    logInfo('Returning tools list', { toolCount: tools.length });
 
    // Helper function to resolve $ref references in JSON schema
    function resolveRefs(
      schema: JsonSchemaProperty | JsonSchemaProperty[],
      rootSchema?: JsonSchema,
    ): JsonSchemaProperty | JsonSchemaProperty[] {
      Iif (!schema || typeof schema !== 'object') return schema;
 
      // Set root schema for reference resolution
      rootSchema ??= schema as JsonSchema;
 
      // Handle arrays
      Iif (Array.isArray(schema)) {
        return schema.map((item) => resolveRefs(item, rootSchema) as JsonSchemaProperty);
      }
 
      // Handle $ref resolution
      if (schema.$ref && typeof schema.$ref === 'string') {
        const refPath = schema.$ref.replace('#/properties/', '');
        const referencedProperty = rootSchema.properties?.[refPath];
 
        if (referencedProperty) {
          // Resolve the referenced property recursively
          const resolvedRef = resolveRefs(referencedProperty, rootSchema) as JsonSchemaProperty;
          // Merge with current properties (excluding $ref)
          const schemaWithoutRef = { ...schema };
          delete schemaWithoutRef.$ref;
          return { ...resolvedRef, ...schemaWithoutRef };
        }
        // If reference can't be resolved, remove $ref and keep other properties
        const schemaWithoutRef = { ...schema };
        delete schemaWithoutRef.$ref;
        return schemaWithoutRef;
      }
 
      // Recursively process all object properties
      const result: JsonSchemaProperty = {};
      for (const [key, value] of Object.entries(schema)) {
        if (key === 'properties' && typeof value === 'object' && value !== null) {
          // Special handling for properties object
          const resolvedProperties: Record<string, JsonSchemaProperty> = {};
          for (const [propKey, propValue] of Object.entries(
            value as Record<string, JsonSchemaProperty>,
          )) {
            resolvedProperties[propKey] = resolveRefs(propValue, rootSchema) as JsonSchemaProperty;
          }
          result[key] = resolvedProperties;
        } else if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
          result[key] = resolveRefs(value as JsonSchemaProperty, rootSchema);
        } else {
          result[key] = value;
        }
      }
 
      return result;
    }
 
    // Remove $schema for Gemini compatibility and ensure proper JSON schema format
    const modifiedTools = tools.map((tool) => {
      let inputSchema = tool.inputSchema;
 
      // Force all input schemas to be type: "object" for MCP compatibility
      Eif (inputSchema && typeof inputSchema === 'object') {
        inputSchema = { ...inputSchema, type: 'object' };
      }
 
      // Resolve $ref references for MCP agent compatibility
      Eif (inputSchema && typeof inputSchema === 'object') {
        const resolved = resolveRefs(inputSchema);
        // Only assign if resolved is an object (not array)
        Eif (resolved && typeof resolved === 'object' && !Array.isArray(resolved)) {
          inputSchema = resolved;
        }
      }
 
      // Remove $schema for Gemini compatibility
      if (inputSchema && typeof inputSchema === 'object' && '$schema' in inputSchema) {
        const cleanedSchema = { ...inputSchema } as Record<string, unknown>;
        delete cleanedSchema.$schema;
        inputSchema = cleanedSchema;
      }
 
      // A tool that declares its own schemes keeps them.
      if (!securitySchemes || tool._meta?.securitySchemes !== undefined) {
        return { ...tool, inputSchema };
      }
      // A tool that opens an app panel also needs the panel resource read. Mirrored in _meta
      // for clients whose descriptor schema drops unknown top-level fields.
      const schemes = tool._meta?.ui ? APP_PANEL_SECURITY_SCHEMES : securitySchemes;
      return {
        ...tool,
        inputSchema,
        securitySchemes: schemes,
        _meta: { ...tool._meta, securitySchemes: schemes },
      };
    });
 
    return {
      tools: modifiedTools,
    };
  };
  // The chat lists the tools of the account it works with. An account it switched to that
  // cannot be used now lists the connection's own; every call is refused until it switches.
  server.setRequestHandler(ListToolsRequestSchema, async (_request, extra) => {
    try {
      return await withChatAccount(extra?.sessionId, () => listTools(extra));
    } catch (error) {
      if (!(error instanceof AccountUnavailableError)) throw error;
      return listTools(extra);
    }
  });
 
  // Call tool handler — all tool execution is wrapped with a handler-level timeout
  // using Promise.race() so the client gets a response early on hang. The underlying
  // work may continue running after the timeout fires, but late results are guarded
  // by the timedOut flag to prevent overwriting the timeout error response.
  const callTool = async (
    request: CallToolRequest,
    extra: { sessionId?: string } | undefined,
    deadline: CallDeadline,
  ): Promise<CallToolResult> => {
    // Capture instance URL early — used for both handlerWork and timeout reporting.
    // Must be resolved before Promise.race so timeout branch doesn't re-derive a
    // potentially different URL after a concurrent instance change.
    const {
      getGitLabApiUrlFromContext: getUrlFromCtx,
      isOAuthEnabled,
      getTokenContext: getCallContext,
    } = await import('./oauth/index');
    // In OAuth mode, use the per-request context URL to avoid bleeding the
    // last-set ConnectionManager instance across concurrent OAuth sessions.
    // When OAuth is enabled but no request context is available (e.g. startup
    // health check, non-OAuth transport), we fall back to GITLAB_BASE_URL as the
    // default instance. This is intentional: the alternative (returning an auth
    // error) would block health monitoring and tool-list initialization. The
    // fallback is safe because GITLAB_BASE_URL is always configured.
    // In static-token mode, prefer the actively selected instance URL so
    // requests continue routing to the current instance.
    const oauthEnabled = isOAuthEnabled();
    if (oauthEnabled) {
      const rejection = toolScopeRejection();
      if (rejection) return rejection;
    }
    const requestScopes = oauthEnabled ? getCallContext()?.gitlabScopes : undefined;
    let declaredIdempotent: boolean | undefined;
    // getGitLabApiUrlFromContext() returns string | undefined; use undefined (not null)
    // so that strict equality checks below correctly detect "no OAuth context".
    const oauthContextUrl = oauthEnabled ? getUrlFromCtx() : undefined;
    const requestInstanceUrl = activeInstanceUrl(oauthEnabled, oauthContextUrl);
 
    const callSessionId = extra?.sessionId;
    if (callSessionId && !managesAccounts(request)) {
      await pinSessionInstance(callSessionId, oauthEnabled, oauthContextUrl, requestInstanceUrl);
    }
    // Whose settings apply, from the authenticated request only.
    const caller = resolveCaller(callSessionId, requestInstanceUrl);
 
    // Tracks whether bootstrap was entered and whether it completed.
    // started: true once we enter the init/introspection path (not set for the
    //   disconnected manage_context bypass which does no GitLab I/O)
    // complete: true after init + introspection succeed (before cache rebuild)
    const bootstrapState: BootstrapState = { started: false, complete: false };
    // A late reportSuccess/reportError from a timed-out handlerWork() must not overwrite the
    // timeout signal already sent to HealthMonitor.
    const timedOut = deadline.isExpired;
 
    // The actual handler logic as a separate async function
    const handlerWork = async (): Promise<CallToolResult> => {
      // In condensed mode, tool/action is captured via request tracker for single-line log
      // In verbose mode, emit per-request INFO logs
      if (LOG_FORMAT === 'verbose') {
        logInfo(`Tool called: ${request.params.name}`);
      }
 
      // Check if authentication is configured
      const { isOAuthEnabled, isAuthenticationConfigured } = await import('./oauth/index');
 
      if (!isAuthenticationConfigured()) {
        // No token configured - return clear error with setup instructions
        throw new Error(
          'GITLAB_TOKEN environment variable is required to execute tools. ' +
            "Run 'npx @structured-world/gitlab-mcp setup' for interactive configuration, " +
            'or set GITLAB_TOKEN manually. ' +
            'Documentation: https://gitlab-mcp.sw.foundation/guide/configuration',
        );
      }
 
      // Use the instance URL captured before Promise.race (requestInstanceUrl)
      // to ensure the entire dispatch path uses the same URL.
      const effectiveInstanceUrl = requestInstanceUrl;
      const connectionManager = ConnectionManager.getInstance();
      const healthMonitor = HealthMonitor.getInstance();
      const toolName = request.params.name;
      let toolArguments = request.params.arguments;
 
      // The caller's settings, checked before anything reaches GitLab. A call is refused
      // when they cannot be read: allowing it could bypass a restriction.
      const { RegistryManager: CallRegistry } = await import('./registry-manager');
      const configuration = await getConfigurationService().resolve(caller);
      const prepared = await prepareScopedCall(
        toolName,
        toolArguments ?? {},
        configuration.policy,
        CallRegistry.getInstance(),
        timedOut,
      );
      if (prepared.rejection) return prepared.rejection;
      toolArguments = prepared.args;
 
      // Early return: instance unreachable for non-context tools
      // (isInstanceReachable treats untracked URLs as reachable before HealthMonitor.initialize)
      const unreachableResult = checkUnreachableInstance(
        toolName,
        toolArguments,
        effectiveInstanceUrl,
        healthMonitor,
      );
      if (unreachableResult) return unreachableResult;
 
      // Configuration tools while disconnected, and the account actions: no bootstrap
      const withoutBootstrap = await tryWithoutBootstrap(
        request,
        toolArguments,
        effectiveInstanceUrl,
        healthMonitor,
        callSessionId,
        requestScopes,
      );
      if (withoutBootstrap) return withoutBootstrap;
 
      // Initialize connection, verify client, and rebuild the per-URL tool cache
      const oauthMode = isOAuthEnabled();
      const bootstrapFailure = await ensureBootstrapped({
        toolName,
        toolArguments,
        effectiveInstanceUrl,
        oauthMode,
        requestScopes,
        connectionManager,
        healthMonitor,
        isTimedOut: timedOut,
        bootstrapState,
      });
      if (bootstrapFailure) return bootstrapFailure;
 
      // Dynamic tool dispatch using the new registry manager
      const toolArgs = request.params.arguments;
      const action = toolArgs && typeof toolArgs.action === 'string' ? toolArgs.action : undefined;
 
      // Access log tracking only runs in condensed mode (verbose mode uses per-line logs)
      if (LOG_FORMAT === 'condensed') {
        const requestTracker = getRequestTracker();
        requestTracker.setToolForCurrentRequest(toolName, action);
        recordCallContext(
          scopeLabel(configuration.policy.scope),
          GITLAB_READ_ONLY_MODE || configuration.policy.readOnly,
        );
      }
 
      try {
        // Import the registry manager
        const { RegistryManager } = await import('./registry-manager');
        const registryManager = RegistryManager.getInstance();
        const definition = registryManager.getTool(toolName, effectiveInstanceUrl, requestScopes);
        declaredIdempotent = definition?.idempotent ?? definition?.annotations?.idempotentHint;
 
        // Check if tool exists and passes all filtering (applied at registry level).
        // Uses per-URL cache so the check is against the correct instance's
        // tier/version/scopes. hasToolHandler + executeTool are not atomic — see
        // comment above on the bootstrap fast-path for context. Here a TOCTOU
        // miss throws, which is caught and converted to a McpError with the
        // message below.
        if (!registryManager.hasToolHandler(toolName, effectiveInstanceUrl)) {
          throw new Error(`Tool '${toolName}' is not available or has been filtered out`);
        }
 
        if (LOG_FORMAT === 'verbose') {
          logInfo(`Executing tool: ${toolName}`);
        }
 
        // Check OAuth context
        const { isOAuthEnabled, getTokenContext } = await import('./oauth/index');
        if (isOAuthEnabled()) {
          const context = getTokenContext();
          logDebug('OAuth context check before tool execution', {
            hasContext: !!context,
            hasToken: !!context?.gitlabToken,
            tool: toolName,
          });
        }
 
        const result = await executeInScope(
          registryManager,
          toolName,
          toolArguments,
          prepared.policy,
          effectiveInstanceUrl,
          requestScopes,
          timedOut,
        );
 
        // Guard against TOCTOU cache miss: hasToolHandler returned true but a
        // concurrent refreshCache swapped the lookup table before executeTool ran.
        // Re-throw so the outer catch converts it to a McpError, consistent with
        // the explicit hasToolHandler check above. Never return JSON.stringify(undefined)
        // which would produce an invalid MCP payload ("text: undefined").
        if (result === undefined) {
          throw new Error(`Tool '${toolName}' is not available or has been filtered out`);
        }
 
        // Report success — skip if handler already timed out (late completion
        // must not overwrite the timeout error already sent to HealthMonitor)
        if (!timedOut()) {
          healthMonitor.reportSuccess(effectiveInstanceUrl);
        }
 
        return formatToolResult(result, definition);
      } catch (error) {
        throwDispatchError(error, toolName, effectiveInstanceUrl, healthMonitor, timedOut());
      }
    };
 
    try {
      // Race all tools against the timeout. For non-idempotent mutations this
      // means the client gets a timeout response while the mutation may still
      // complete — but the alternative (no timeout) leaves bootstrap unbounded
      // if the instance is hung. The timedOut flag prevents late reportSuccess/
      // reportError from overwriting the timeout health signal.
      const result = await Promise.race([runWithCaller(caller, handlerWork), deadline.expired]);
 
      // The deadline expired — handler is still running but we respond
      if (result === HANDLER_TIMEOUT) {
        return handlerTimeoutResult(
          request,
          declaredIdempotent,
          bootstrapState,
          requestInstanceUrl,
        );
      }
 
      return result;
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : String(error);
      logError(`Error in tool handler: ${errMsg}`);
      recordToolError(errMsg);
 
      // Try to convert to structured error for better LLM feedback
      const toolName = request.params.name;
      const toolArgs = request.params.arguments;
      const structuredError = toStructuredError(error, toolName, toolArgs, declaredIdempotent);
 
      if (structuredError) {
        logDebug('Returning structured error response', { structuredError });
        return withReauthChallenge(errorToolResult(structuredError), error);
      }
 
      // Fallback to original error format
      const errorMessage = error instanceof Error ? error.message : String(error);
      return withReauthChallenge(errorToolResult({ error: errorMessage }), error);
    }
  };
  // A call runs as the account its chat works with; one that cannot be used refuses it.
  // Managing the accounts needs no account's token, so it also runs when the chosen one
  // cannot be used: that is how the chat switches away from it.
  // The timeout starts when the call arrives: resolving the account (a token refresh, a
  // wait for another replica's refresh lease) counts against it like the handler does.
  server.setRequestHandler(CallToolRequestSchema, (request, extra) => {
    const deadline = startCallDeadline();
    const signal = extra?.signal
      ? AbortSignal.any([extra.signal, deadline.signal])
      : deadline.signal;
    return runWithMcpServer(
      server,
      async () => {
        try {
          if (managesAccounts(request)) return await callTool(request, extra, deadline);
          let running = false;
          const call = withChatAccount(extra?.sessionId, async () => {
            // The client was already answered with a timeout: the tool must not run behind it.
            if (deadline.isExpired()) return undefined;
            running = true;
            return callTool(request, extra, deadline);
          });
          const first = await Promise.race([call, deadline.expired]);
          if (first !== HANDLER_TIMEOUT && first !== undefined) return first;
          // A running handler answers its own timeout, with what its bootstrap reached.
          const answered = running ? await call : undefined;
          if (answered) return answered;
          call.catch((error: unknown) =>
            logDebug('Account resolution failed after the call timed out', { err: error }),
          );
          return handlerTimeoutResult(
            request,
            undefined,
            { started: false, complete: false },
            GITLAB_BASE_URL,
          );
        } catch (error) {
          if (!(error instanceof AccountUnavailableError)) throw error;
          return errorToolResult({ error: error.message });
        } finally {
          deadline.clear();
        }
      },
      signal,
    );
  });
}