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 | 18x 18x 18x 14x 14x 1x 13x 13x 13x 5x 5x 9x 2x 2x 7x 1x 1x 6x 5x 5x 5x 3x 2x 3x 1x 1x 2x 1x 1x 1x 5x 5x 3x 5x 2x 5x 5x 6x 6x 18x 17x 17x 14x 11x 18x 36x 36x 36x 14x 14x 7x 7x 22x 11x 11x 2x 9x 5x 4x 7x 7x 7x 7x 11x 11x 5x 6x 1x 5x 1x 4x 1x 3x 1x 2x 1x 11x 11x 1x 11x 10x 10x 1x 9x 9x 1x 11x 18x 2x 18x 1x 18x 1x 18x 1x 18x 10x 10x 18x 9x 9x 9x 9x 3x 3x 6x 3x 3x 3x 3x 9x 18x 28x 28x 18x 8x 8x 8x 8x 8x 1x 18x 50x | /**
* Structured Error Handler
*
* Transforms GitLab API errors into structured, actionable responses
* that help LLMs self-correct and provide guidance for users.
*
* Integrates with ConnectionManager to detect tier restrictions based on
* actual GitLab instance capabilities, not static mappings.
*/
import { ConnectionManager } from "../services/ConnectionManager.js";
import { GitLabFeatures, GitLabTier as InternalTier } from "../services/GitLabVersionDetector.js";
import { parseVersion } from "./version.js";
/**
* Display-friendly tier type with capitalized values for API responses.
* Distinct from InternalTier (lowercase) - converted via normalizeTier().
*/
export type GitLabTier = "Free" | "Premium" | "Ultimate";
// ============================================================================
// Error Types
// ============================================================================
/**
* Base structured error interface
*/
export interface StructuredError {
/** Error classification code */
error_code: string;
/** Tool that triggered the error */
tool: string;
/** Action that was attempted */
action: string;
/** Human-readable error message */
message: string;
/** Suggested fix for the error */
suggested_fix?: string;
}
/**
* Validation error for invalid action parameters
*/
export interface ActionValidationError extends StructuredError {
error_code:
| "MISSING_REQUIRED_FIELD"
| "INVALID_ACTION"
| "FIELD_NOT_ALLOWED"
| "TYPE_MISMATCH"
| "VALIDATION_ERROR";
/** Fields that are missing but required */
missing_fields?: string[];
/** Fields with invalid values */
invalid_fields?: Array<{
field: string;
expected: string;
received: string;
}>;
/** List of valid actions for this tool */
valid_actions?: string[];
/** Required fields for each action */
action_required_fields?: Record<string, string[]>;
}
/**
* Alternative action available on a different tier
*
* Note: This interface uses snake_case for JSON serialization in API responses.
*/
export interface TierAlternative {
/** Action description */
action: string;
/** Detailed description of the alternative */
description: string;
/** Tier where this alternative is available (snake_case for JSON output) */
available_on: GitLabTier;
}
/**
* Error for tier-restricted features
*/
export interface TierRestrictedError extends StructuredError {
error_code: "TIER_RESTRICTED";
/** HTTP status code from GitLab */
http_status: number;
/** Required tier for this feature */
tier_required: GitLabTier;
/** Current tier if detectable */
current_tier?: GitLabTier;
/** Human-readable feature name */
feature_name: string;
/** Alternative approaches */
alternatives?: TierAlternative[];
/** Documentation URL */
docs_url?: string;
/** Upgrade URL */
upgrade_url?: string;
}
/**
* Error for permission denied (not tier-related)
*/
export interface PermissionDeniedError extends StructuredError {
error_code: "PERMISSION_DENIED";
/** HTTP status code from GitLab */
http_status: number;
/** Required access level */
required_access?: string;
/** Alternative approaches */
alternatives?: TierAlternative[];
}
/**
* Error for resource not found
*/
export interface NotFoundError extends StructuredError {
error_code: "NOT_FOUND";
/** HTTP status code from GitLab */
http_status: number;
/** Resource type that wasn't found */
resource_type?: string;
/** Resource identifier that was searched */
resource_id?: string;
}
/**
* Generic API error
*/
export interface ApiError extends StructuredError {
error_code: "API_ERROR" | "RATE_LIMITED" | "SERVER_ERROR";
/** HTTP status code from GitLab */
http_status: number;
/** Raw error from GitLab */
gitlab_error?: string;
}
/**
* Error for version-restricted widget parameters
*/
export interface VersionRestrictedError extends StructuredError {
error_code: "VERSION_RESTRICTED";
/** Widget type that is restricted */
widget: string;
/** Parameter name that maps to the widget */
parameter: string;
/** Required GitLab version for this widget */
required_version: string;
/** Detected GitLab instance version */
detected_version: string;
/** Required tier (if also tier-restricted) */
required_tier?: GitLabTier;
/** Current tier */
current_tier?: GitLabTier;
/** Documentation URL */
docs_url?: string;
}
/**
* Timeout error for API requests that exceeded the timeout limit
*/
export interface TimeoutError extends StructuredError {
error_code: "TIMEOUT";
/** Timeout duration in milliseconds */
timeout_ms: number;
/** Whether the request can be retried (idempotent operation) */
retryable: boolean;
}
/**
* Union type of all structured errors
*/
export type GitLabStructuredError =
| ActionValidationError
| TierRestrictedError
| VersionRestrictedError
| PermissionDeniedError
| NotFoundError
| ApiError
| TimeoutError;
// ============================================================================
// Tier Restriction Detection
// ============================================================================
/**
* Information about a tier-restricted feature
*/
interface TierRestrictionInfo {
/** Feature key from GitLabFeatures */
feature: keyof GitLabFeatures;
/** Human-readable feature name */
name: string;
/** Required tier for this feature */
requiredTier: GitLabTier;
/** Current instance tier */
currentTier?: GitLabTier;
/** Alternative approaches */
alternatives: TierAlternative[];
/** Documentation URL */
docsUrl: string;
}
/**
* Mapping of features to their metadata (name, docs, alternatives)
* Used for generating helpful error messages
*/
const FEATURE_METADATA: Record<
keyof GitLabFeatures,
{
name: string;
requiredTier: GitLabTier;
docsUrl: string;
alternatives: TierAlternative[];
}
> = {
workItems: {
name: "Work Items",
requiredTier: "Free",
docsUrl: "https://docs.gitlab.com/ee/user/project/work_items/",
alternatives: [],
},
epics: {
name: "Epics",
requiredTier: "Premium",
docsUrl: "https://docs.gitlab.com/ee/user/group/epics/",
alternatives: [
{
action: "Use issues for tracking",
description: "Create issues with labels to organize work instead of epics",
available_on: "Free",
},
{
action: "Use milestones",
description: "Group related issues under milestones for release planning",
available_on: "Free",
},
],
},
iterations: {
name: "Iterations",
requiredTier: "Premium",
docsUrl: "https://docs.gitlab.com/ee/user/group/iterations/",
alternatives: [
{
action: "Use milestones",
description: "Use milestones to track time-boxed work periods",
available_on: "Free",
},
],
},
roadmaps: {
name: "Roadmaps",
requiredTier: "Premium",
docsUrl: "https://docs.gitlab.com/ee/user/group/roadmap/",
alternatives: [
{
action: "Use milestone views",
description: "View milestones timeline for basic roadmap functionality",
available_on: "Free",
},
],
},
portfolioManagement: {
name: "Portfolio Management",
requiredTier: "Ultimate",
docsUrl: "https://docs.gitlab.com/ee/user/group/planning_hierarchy/",
alternatives: [
{
action: "Use group-level milestones",
description: "Track progress across projects using group milestones",
available_on: "Free",
},
],
},
advancedSearch: {
name: "Advanced Search",
requiredTier: "Premium",
docsUrl: "https://docs.gitlab.com/ee/user/search/advanced_search.html",
alternatives: [
{
action: "Use basic search",
description: "Use standard GitLab search functionality",
available_on: "Free",
},
],
},
codeReview: {
name: "Code Review Analytics",
requiredTier: "Premium",
docsUrl: "https://docs.gitlab.com/ee/user/analytics/code_review_analytics.html",
alternatives: [],
},
securityDashboard: {
name: "Security Dashboard",
requiredTier: "Ultimate",
docsUrl: "https://docs.gitlab.com/ee/user/application_security/security_dashboard/",
alternatives: [],
},
complianceFramework: {
name: "Compliance Framework",
requiredTier: "Ultimate",
docsUrl: "https://docs.gitlab.com/ee/user/project/settings/compliance_frameworks.html",
alternatives: [],
},
valueStreamAnalytics: {
name: "Value Stream Analytics",
requiredTier: "Premium",
docsUrl: "https://docs.gitlab.com/ee/user/group/value_stream_analytics/",
alternatives: [],
},
customFields: {
name: "Custom Fields",
requiredTier: "Ultimate",
docsUrl: "https://docs.gitlab.com/ee/user/project/working_with_projects.html",
alternatives: [
{
action: "Use labels",
description: "Use labels to categorize and tag work items",
available_on: "Free",
},
],
},
okrs: {
name: "OKRs (Objectives and Key Results)",
requiredTier: "Ultimate",
docsUrl: "https://docs.gitlab.com/ee/user/okrs/",
alternatives: [
{
action: "Use issues with labels",
description: "Track objectives as issues with specific labels",
available_on: "Free",
},
],
},
healthStatus: {
name: "Health Status",
requiredTier: "Ultimate",
docsUrl: "https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#health-status",
alternatives: [
{
action: "Use labels for status",
description: "Create labels like 'on-track', 'at-risk', 'needs-attention'",
available_on: "Free",
},
],
},
weight: {
name: "Issue Weight",
requiredTier: "Premium",
docsUrl: "https://docs.gitlab.com/ee/user/project/issues/issue_weight.html",
alternatives: [
{
action: "Use labels for estimation",
description: "Create labels like 'size::S', 'size::M', 'size::L' for estimation",
available_on: "Free",
},
],
},
multiLevelEpics: {
name: "Multi-level Epics",
requiredTier: "Ultimate",
docsUrl:
"https://docs.gitlab.com/ee/user/group/epics/manage_epics.html#multi-level-child-epics",
alternatives: [
{
action: "Use flat epics",
description: "Organize work with single-level epics (Premium)",
available_on: "Premium",
},
],
},
serviceDesk: {
name: "Service Desk",
requiredTier: "Premium",
docsUrl: "https://docs.gitlab.com/ee/user/project/service_desk/",
alternatives: [],
},
requirements: {
name: "Requirements Management",
requiredTier: "Ultimate",
docsUrl: "https://docs.gitlab.com/ee/user/project/requirements/",
alternatives: [
{
action: "Use issues",
description: "Track requirements as issues with a dedicated label",
available_on: "Free",
},
],
},
qualityManagement: {
name: "Quality Management",
requiredTier: "Ultimate",
docsUrl: "https://docs.gitlab.com/ee/ci/testing/",
alternatives: [],
},
timeTracking: {
name: "Time Tracking",
requiredTier: "Premium",
docsUrl: "https://docs.gitlab.com/ee/user/project/time_tracking.html",
alternatives: [],
},
crmContacts: {
name: "CRM Contacts",
requiredTier: "Ultimate",
docsUrl: "https://docs.gitlab.com/ee/user/crm/",
alternatives: [],
},
vulnerabilities: {
name: "Vulnerability Management",
requiredTier: "Ultimate",
docsUrl: "https://docs.gitlab.com/ee/user/application_security/vulnerabilities/",
alternatives: [],
},
errorTracking: {
name: "Error Tracking",
requiredTier: "Ultimate",
docsUrl: "https://docs.gitlab.com/ee/operations/error_tracking.html",
alternatives: [],
},
designManagement: {
name: "Design Management",
requiredTier: "Premium",
docsUrl: "https://docs.gitlab.com/ee/user/project/issues/design_management.html",
alternatives: [],
},
linkedResources: {
name: "Linked Resources",
requiredTier: "Premium",
docsUrl: "https://docs.gitlab.com/ee/user/project/issues/related_issues.html",
alternatives: [],
},
emailParticipants: {
name: "Email Participants",
requiredTier: "Premium",
docsUrl:
"https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#add-an-email-participant",
alternatives: [],
},
};
/**
* Detect if the error is due to a tier restriction
*
* Uses ConnectionManager to check actual instance capabilities
* and analyzes tool parameters for context-aware detection
*/
function detectTierRestriction(
tool: string,
action: string,
toolArgs?: Record<string, unknown>
): TierRestrictionInfo | null {
let connectionManager: ConnectionManager;
try {
connectionManager = ConnectionManager.getInstance();
} catch {
// Connection not initialized - cannot detect tier
return null;
}
// Get current tier for the error response
const currentTierRaw = connectionManager.getTier();
const currentTier = normalizeTier(currentTierRaw);
// Check for work item type restrictions
if (tool === "browse_work_items" || tool === "manage_work_item") {
const restriction = checkWorkItemTypeRestriction(connectionManager, toolArgs, currentTier);
if (restriction) return restriction;
}
// Check for iterations
if (tool === "browse_iterations") {
Eif (!connectionManager.isFeatureAvailable("iterations")) {
return createRestrictionInfo("iterations", currentTier);
}
}
// Check for group webhooks (tool name pattern)
if ((tool === "browse_webhooks" || tool === "manage_webhook") && toolArgs?.scope === "group") {
// Group webhooks require Premium - check if we have serviceDesk (Premium feature) as proxy
Eif (!connectionManager.isFeatureAvailable("serviceDesk")) {
return {
feature: "serviceDesk", // Using serviceDesk as proxy for Premium tier
name: "Group Webhooks",
requiredTier: "Premium",
currentTier,
alternatives: [
{
action: "Use project-level webhooks",
description: "Configure webhooks on individual projects instead",
available_on: "Free",
},
],
docsUrl: "https://docs.gitlab.com/ee/user/project/integrations/webhooks.html",
};
}
}
return null;
}
/**
* Check if work item types in the request require higher tier
*/
function checkWorkItemTypeRestriction(
connectionManager: ConnectionManager,
toolArgs?: Record<string, unknown>,
currentTier?: GitLabTier
): TierRestrictionInfo | null {
Iif (!toolArgs) return null;
// Extract work item types from various parameter formats
const types = extractWorkItemTypes(toolArgs);
// Check for EPIC
if (types.includes("EPIC")) {
if (!connectionManager.isFeatureAvailable("epics")) {
return createRestrictionInfo("epics", currentTier);
}
}
// Check for OBJECTIVE/KEY_RESULT (OKRs)
if (types.includes("OBJECTIVE") || types.includes("KEY_RESULT")) {
Eif (!connectionManager.isFeatureAvailable("okrs")) {
return createRestrictionInfo("okrs", currentTier);
}
}
// Check for REQUIREMENT
if (types.includes("REQUIREMENT")) {
Eif (!connectionManager.isFeatureAvailable("requirements")) {
return createRestrictionInfo("requirements", currentTier);
}
}
return null;
}
/**
* Extract work item types from tool arguments
*/
function extractWorkItemTypes(toolArgs: Record<string, unknown>): string[] {
const types: string[] = [];
// Handle 'types' array parameter (browse_work_items)
if (Array.isArray(toolArgs.types)) {
types.push(...toolArgs.types.map(t => String(t).toUpperCase()));
}
// Handle 'workItemType' string parameter (manage_work_item)
if (typeof toolArgs.workItemType === "string") {
types.push(toolArgs.workItemType.toUpperCase());
}
// Handle 'type' string parameter (alternative naming)
Iif (typeof toolArgs.type === "string") {
types.push(toolArgs.type.toUpperCase());
}
return types;
}
/**
* Create TierRestrictionInfo from feature key
*/
function createRestrictionInfo(
feature: keyof GitLabFeatures,
currentTier?: GitLabTier
): TierRestrictionInfo {
const metadata = FEATURE_METADATA[feature];
return {
feature,
name: metadata.name,
requiredTier: metadata.requiredTier,
currentTier,
alternatives: metadata.alternatives,
docsUrl: metadata.docsUrl,
};
}
/**
* Normalize tier string to display GitLabTier type.
* Converts InternalTier (lowercase: "free", "premium", "ultimate")
* to display GitLabTier (capitalized: "Free", "Premium", "Ultimate").
*/
export function normalizeTier(tier: string | InternalTier): GitLabTier {
const lower = tier.toLowerCase();
if (lower === "ultimate" || lower === "gold") return "Ultimate";
if (lower === "premium" || lower === "silver") return "Premium";
return "Free";
}
// ============================================================================
// Error Handler
// ============================================================================
/**
* Raw GitLab API error shape
*/
export interface GitLabApiErrorResponse {
status: number;
message?: string;
error?: string;
error_description?: string;
}
/**
* Transform a GitLab API error into a structured error response
*
* @param error - Raw error from GitLab API
* @param tool - Tool name that triggered the error
* @param action - Action that was attempted
* @param toolArgs - Original tool arguments (used for parameter-aware tier detection)
* @returns Structured error with actionable information
*/
export function handleGitLabError(
error: GitLabApiErrorResponse,
tool: string,
action: string,
toolArgs?: Record<string, unknown>
): GitLabStructuredError {
const { status, message, error: errorMsg, error_description } = error;
const rawMessage = message ?? errorMsg ?? error_description ?? "Unknown error";
// 403 Forbidden - could be tier restriction or permission issue
if (status === 403) {
// Check for tier restrictions using ConnectionManager and tool parameters
const tierRestriction = detectTierRestriction(tool, action, toolArgs);
if (tierRestriction) {
return createTierRestrictedError(tool, action, status, tierRestriction);
}
return createPermissionDeniedError(tool, action, status, rawMessage);
}
// 404 Not Found - resource doesn't exist or no access
if (status === 404) {
return createNotFoundError(tool, action, status, rawMessage);
}
// 429 Rate Limited
if (status === 429) {
return {
error_code: "RATE_LIMITED",
tool,
action,
http_status: status,
message: "Rate limit exceeded. Please wait before retrying.",
suggested_fix: "Wait a few minutes and try again, or reduce request frequency",
gitlab_error: rawMessage,
};
}
// 5xx Server Errors
if (status >= 500) {
return {
error_code: "SERVER_ERROR",
tool,
action,
http_status: status,
message: "GitLab server error. The service may be temporarily unavailable.",
suggested_fix: "Wait and retry. If the problem persists, check GitLab status page.",
gitlab_error: rawMessage,
};
}
// Generic API error for other status codes
return {
error_code: "API_ERROR",
tool,
action,
http_status: status,
message: rawMessage,
suggested_fix: "Check the GitLab API documentation for this endpoint",
gitlab_error: rawMessage,
};
}
/**
* Create a tier-restricted error response
*/
function createTierRestrictedError(
tool: string,
action: string,
status: number,
restriction: TierRestrictionInfo
): TierRestrictedError {
return {
error_code: "TIER_RESTRICTED",
tool,
action,
http_status: status,
tier_required: restriction.requiredTier,
current_tier: restriction.currentTier,
feature_name: restriction.name,
message: `${restriction.name} requires GitLab ${restriction.requiredTier} or higher`,
suggested_fix:
restriction.alternatives.length > 0
? `Upgrade to GitLab ${restriction.requiredTier}, or use one of the alternatives`
: `Upgrade to GitLab ${restriction.requiredTier} to access this feature`,
alternatives: restriction.alternatives.length > 0 ? restriction.alternatives : undefined,
docs_url: restriction.docsUrl,
upgrade_url: "https://about.gitlab.com/pricing/",
};
}
/**
* Create a permission denied error response
*/
function createPermissionDeniedError(
tool: string,
action: string,
status: number,
rawMessage: string
): PermissionDeniedError {
const baseSuggestedFix =
"Check your access level for this project/group. Reporter access or higher may be required.";
// Include raw message if it provides additional context
const suggestedFix =
rawMessage && rawMessage !== "Unknown error" && !rawMessage.includes("403")
? `${baseSuggestedFix} GitLab message: ${rawMessage}`
: baseSuggestedFix;
return {
error_code: "PERMISSION_DENIED",
tool,
action,
http_status: status,
message: "You don't have permission for this action",
suggested_fix: suggestedFix,
alternatives: [
{
action: "Verify your access level",
description: "Check your role in the project settings or contact a project maintainer",
available_on: "Free",
},
],
};
}
/**
* Create a not found error response
*/
function createNotFoundError(
tool: string,
action: string,
status: number,
rawMessage: string
): NotFoundError {
// Try to extract resource info from the message
let resourceType: string | undefined;
let resourceId: string | undefined;
const lowerMessage = rawMessage.toLowerCase();
if (lowerMessage.includes("project")) {
resourceType = "project";
} else if (lowerMessage.includes("merge request") || lowerMessage.includes("mr")) {
resourceType = "merge_request";
} else if (lowerMessage.includes("issue")) {
resourceType = "issue";
} else if (lowerMessage.includes("pipeline")) {
resourceType = "pipeline";
} else if (lowerMessage.includes("branch")) {
resourceType = "branch";
} else if (lowerMessage.includes("user")) {
resourceType = "user";
}
// Try to extract path-like identifier first (e.g., "'group/project'")
const pathMatch = rawMessage.match(/['"]([a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)+)['"]/);
if (pathMatch) {
resourceId = pathMatch[1];
}
// Try to extract numeric ID from the message (e.g., "Project 12345 not found")
// Strategy: Look for numbers that appear after resource keywords, or are > 3 digits
// This avoids matching HTTP status codes like "404 Not Found"
if (!resourceId) {
// First try: look for ID after resource type keyword (e.g., "Project 123")
const contextMatch = rawMessage.match(
/(?:project|issue|merge.?request|mr|pipeline|branch|user|group)\s+#?(\d+)/i
);
if (contextMatch) {
resourceId = contextMatch[1];
} else {
// Fallback: match numbers with 4+ digits (unlikely to be status codes)
const longIdMatch = rawMessage.match(/\b(\d{4,})\b/);
if (longIdMatch) {
resourceId = longIdMatch[1];
}
}
}
return {
error_code: "NOT_FOUND",
tool,
action,
http_status: status,
message: "Resource not found or you don't have access to it",
suggested_fix:
"Verify the ID/path is correct and you have at least Reporter access to the project",
resource_type: resourceType,
resource_id: resourceId,
};
}
// ============================================================================
// Validation Error Helpers
// ============================================================================
/**
* Create a validation error for missing required fields
*/
export function createMissingFieldsError(
tool: string,
action: string,
missingFields: string[],
actionRequiredFields?: Record<string, string[]>
): ActionValidationError {
return {
error_code: "MISSING_REQUIRED_FIELD",
tool,
action,
message: `Missing required field(s): ${missingFields.join(", ")}`,
missing_fields: missingFields,
suggested_fix: `Add required fields: ${missingFields.join(", ")}`,
action_required_fields: actionRequiredFields,
};
}
/**
* Create a validation error for invalid action
*/
export function createInvalidActionError(
tool: string,
action: string,
validActions: string[]
): ActionValidationError {
return {
error_code: "INVALID_ACTION",
tool,
action,
message: `Invalid action '${action}'. Valid actions are: ${validActions.join(", ")}`,
suggested_fix: `Use one of the valid actions: ${validActions.join(", ")}`,
valid_actions: validActions,
};
}
/**
* Create a validation error for type mismatch
*/
export function createTypeMismatchError(
tool: string,
action: string,
field: string,
expected: string,
received: string
): ActionValidationError {
return {
error_code: "TYPE_MISMATCH",
tool,
action,
message: `Type mismatch for field '${field}': expected ${expected}, got ${received}`,
invalid_fields: [{ field, expected, received }],
suggested_fix: `Provide a ${expected} value for '${field}'`,
};
}
/**
* Create a generic validation error from Zod error
*/
export function createValidationError(
tool: string,
action: string,
zodMessage: string
): ActionValidationError {
return {
error_code: "VALIDATION_ERROR",
tool,
action,
message: zodMessage,
suggested_fix: "Check the tool documentation for correct parameter format",
};
}
// ============================================================================
// Timeout Error Helper
// ============================================================================
/**
* Create a timeout error response
*
* @param tool - Tool name that triggered the timeout
* @param action - Action that was attempted
* @param timeoutMs - Timeout duration in milliseconds
* @param retryable - Whether the operation is idempotent and can be retried
*/
export function createTimeoutError(
tool: string,
action: string,
timeoutMs: number,
retryable: boolean = false
): TimeoutError {
const retryHint = retryable
? " This is a read-only operation - you can safely retry."
: " This is a write operation - check if it completed before retrying.";
return {
error_code: "TIMEOUT",
tool,
action,
timeout_ms: timeoutMs,
retryable,
message: `Request timed out after ${timeoutMs}ms`,
suggested_fix: `The GitLab server is slow to respond. Try again later or increase GITLAB_API_TIMEOUT_MS.${retryHint}`,
};
}
// ============================================================================
// Version Restricted Error Helper
// ============================================================================
/**
* Create a version-restricted error for widget parameters
*
* @param tool - Tool name that triggered the error
* @param action - Action that was attempted
* @param widget - Widget type that is restricted
* @param parameter - Parameter name that maps to the widget
* @param requiredVersion - Minimum required GitLab version
* @param detectedVersion - Detected GitLab instance version
* @param requiredTier - Required tier (if also tier-restricted)
* @param currentTier - Current instance tier
*/
export function createVersionRestrictedError(
tool: string,
action: string,
widget: string,
parameter: string,
requiredVersion: string,
detectedVersion: string,
requiredTier?: GitLabTier,
currentTier?: GitLabTier
): VersionRestrictedError {
// Determine which constraints are violated
const tierHierarchy: Record<GitLabTier, number> = { Free: 0, Premium: 1, Ultimate: 2 };
const isTierInsufficient =
requiredTier && currentTier && tierHierarchy[requiredTier] > tierHierarchy[currentTier];
// Determine which constraints are actually violated
const isVersionSufficient = parseVersion(detectedVersion) >= parseVersion(requiredVersion);
let suggestedFix: string;
let message: string;
if (isTierInsufficient && isVersionSufficient) {
// Only tier is insufficient
message = `Widget '${widget}' (parameter '${parameter}') requires GitLab ${requiredTier} tier (current: ${currentTier})`;
suggestedFix = `Upgrade to GitLab ${requiredTier} tier to use the '${parameter}' parameter`;
} else if (isTierInsufficient) {
// Both version and tier are insufficient
message = `Widget '${widget}' (parameter '${parameter}') requires GitLab >= ${requiredVersion} and ${requiredTier} tier (detected: ${detectedVersion}, tier: ${currentTier})`;
suggestedFix = `Upgrade GitLab to version ${requiredVersion}+ and ${requiredTier} tier to use the '${parameter}' parameter`;
} else {
// Only version is insufficient
message = `Widget '${widget}' (parameter '${parameter}') requires GitLab >= ${requiredVersion} (detected: ${detectedVersion})`;
suggestedFix = `Upgrade GitLab to version ${requiredVersion} or higher to use the '${parameter}' parameter`;
}
return {
error_code: "VERSION_RESTRICTED",
tool,
action,
widget,
parameter,
required_version: requiredVersion,
detected_version: detectedVersion,
required_tier: isTierInsufficient ? requiredTier : undefined,
current_tier: isTierInsufficient ? currentTier : undefined,
message,
suggested_fix: suggestedFix,
docs_url: "https://docs.gitlab.com/ee/user/project/work_items/",
};
}
/**
* Parse timeout error from error message
* Returns timeout value in ms if the error is a timeout error, null otherwise
*/
export function parseTimeoutError(errorMessage: string): number | null {
const match = errorMessage.match(/GitLab API timeout after (\d+)ms/);
return match ? parseInt(match[1], 10) : null;
}
// ============================================================================
// Custom Error Class
// ============================================================================
/**
* Custom error class for structured tool errors
*
* Allows throwing structured errors that can be caught and serialized
*/
export class StructuredToolError extends Error {
public readonly structuredError: GitLabStructuredError;
constructor(structuredError: GitLabStructuredError) {
super(structuredError.message);
this.name = "StructuredToolError";
this.structuredError = structuredError;
// Maintain proper stack trace
Eif (Error.captureStackTrace) {
Error.captureStackTrace(this, StructuredToolError);
}
}
/**
* Get the structured error as a plain object
*/
toJSON(): GitLabStructuredError {
return this.structuredError;
}
}
/**
* Check if an error is a StructuredToolError
*/
export function isStructuredToolError(error: unknown): error is StructuredToolError {
return error instanceof StructuredToolError;
}
|