All files / src/entities/refs registry.ts

98.11% Statements 104/106
96.36% Branches 53/55
100% Functions 6/6
100% Lines 94/94

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 28217x 17x 17x 17x   17x                   17x                         11x     11x 1x     10x   10x   2x 2x           2x 2x 2x       2x 2x           1x 1x 1x       1x 1x           1x 1x 1x       1x 1x                                                 20x     20x 1x     19x   19x   1x 1x             1x 1x 1x     1x                               5x   5x   5x 5x 5x 1x 5x 5x 5x 5x 1x 5x 1x   5x             1x 1x 1x 1x                         4x   4x 4x   4x 4x 4x 4x 1x 4x 1x   4x             2x 2x   2x   2x             1x 1x 1x 1x                   3x   3x   3x 3x   3x             1x 1x 1x 1x                             17x 2x           17x 3x           17x 3x 1x 2x   2x    
import * as z from "zod";
import { BrowseRefsSchema } from "./schema-readonly";
import { ManageRefSchema } from "./schema";
import { gitlab, toQuery } from "../../utils/gitlab-api";
import { ToolRegistry, EnhancedToolDefinition } from "../../types";
import { isActionDenied } from "../../config";
 
/**
 * Refs tools registry - 2 CQRS tools
 *
 * browse_refs (Query): list_branches, get_branch, list_tags, get_tag,
 *                      list_protected_branches, get_protected_branch, list_protected_tags
 * manage_ref (Command): create_branch, delete_branch, protect_branch, unprotect_branch,
 *                       update_branch_protection, create_tag, delete_tag, protect_tag, unprotect_tag
 */
export const refsToolRegistry: ToolRegistry = new Map<string, EnhancedToolDefinition>([
  // ============================================================================
  // browse_refs - CQRS Query Tool (discriminated union schema)
  // TypeScript automatically narrows types in each switch case
  // ============================================================================
  [
    "browse_refs",
    {
      name: "browse_refs",
      description:
        "Inspect branches, tags, and their protection rules. Actions: list_branches, get_branch, list_tags, get_tag, list_protected_branches, get_protected_branch, list_protected_tags (protection details and access levels). Related: manage_ref to create/delete/protect, browse_commits for commit history.",
      inputSchema: z.toJSONSchema(BrowseRefsSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const input = BrowseRefsSchema.parse(args);
 
        // Runtime validation: reject denied actions even if they bypass schema filtering
        if (isActionDenied("browse_refs", input.action)) {
          throw new Error(`Action '${input.action}' is not allowed for browse_refs tool`);
        }
 
        const encodedProjectId = encodeURIComponent(input.project_id);
 
        switch (input.action) {
          case "list_branches": {
            const { action: _action, project_id: _projectId, ...queryOptions } = input;
            return gitlab.get(`projects/${encodedProjectId}/repository/branches`, {
              query: toQuery(queryOptions, []),
            });
          }
 
          case "get_branch": {
            const { branch } = input;
            const encodedBranch = encodeURIComponent(branch);
            return gitlab.get(`projects/${encodedProjectId}/repository/branches/${encodedBranch}`);
          }
 
          case "list_tags": {
            const { action: _action, project_id: _projectId, ...queryOptions } = input;
            return gitlab.get(`projects/${encodedProjectId}/repository/tags`, {
              query: toQuery(queryOptions, []),
            });
          }
 
          case "get_tag": {
            const { tag_name } = input;
            const encodedTagName = encodeURIComponent(tag_name);
            return gitlab.get(`projects/${encodedProjectId}/repository/tags/${encodedTagName}`);
          }
 
          case "list_protected_branches": {
            const { action: _action, project_id: _projectId, ...queryOptions } = input;
            return gitlab.get(`projects/${encodedProjectId}/protected_branches`, {
              query: toQuery(queryOptions, []),
            });
          }
 
          case "get_protected_branch": {
            const { name } = input;
            const encodedName = encodeURIComponent(name);
            return gitlab.get(`projects/${encodedProjectId}/protected_branches/${encodedName}`);
          }
 
          case "list_protected_tags": {
            const { action: _action, project_id: _projectId, ...queryOptions } = input;
            return gitlab.get(`projects/${encodedProjectId}/protected_tags`, {
              query: toQuery(queryOptions, []),
            });
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
 
  // ============================================================================
  // manage_ref - CQRS Command Tool (discriminated union schema)
  // TypeScript automatically narrows types in each switch case
  // ============================================================================
  [
    "manage_ref",
    {
      name: "manage_ref",
      description:
        "Create, delete, and protect branches and tags. Actions: create_branch (from ref), delete_branch, protect_branch (set allowed roles), unprotect_branch, update_branch_protection, create_tag (annotated or lightweight), delete_tag, protect_tag, unprotect_tag. Related: browse_refs for inspection.",
      inputSchema: z.toJSONSchema(ManageRefSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const input = ManageRefSchema.parse(args);
 
        // Runtime validation: reject denied actions even if they bypass schema filtering
        if (isActionDenied("manage_ref", input.action)) {
          throw new Error(`Action '${input.action}' is not allowed for manage_ref tool`);
        }
 
        const encodedProjectId = encodeURIComponent(input.project_id);
 
        switch (input.action) {
          case "create_branch": {
            const { branch, ref } = input;
            return gitlab.post(`projects/${encodedProjectId}/repository/branches`, {
              body: { branch, ref },
              contentType: "json",
            });
          }
 
          case "delete_branch": {
            const { branch } = input;
            const encodedBranch = encodeURIComponent(branch);
            await gitlab.delete(
              `projects/${encodedProjectId}/repository/branches/${encodedBranch}`
            );
            return { deleted: true, branch };
          }
 
          case "protect_branch": {
            const {
              action: _action,
              project_id: _projectId,
              name,
              push_access_level,
              merge_access_level,
              unprotect_access_level,
              allow_force_push,
              allowed_to_push,
              allowed_to_merge,
              allowed_to_unprotect,
              code_owner_approval_required,
            } = input;
 
            const body: Record<string, unknown> = { name };
 
            if (push_access_level !== undefined) body.push_access_level = push_access_level;
            if (merge_access_level !== undefined) body.merge_access_level = merge_access_level;
            if (unprotect_access_level !== undefined)
              body.unprotect_access_level = unprotect_access_level;
            if (allow_force_push !== undefined) body.allow_force_push = allow_force_push;
            Iif (allowed_to_push !== undefined) body.allowed_to_push = allowed_to_push;
            Iif (allowed_to_merge !== undefined) body.allowed_to_merge = allowed_to_merge;
            if (allowed_to_unprotect !== undefined)
              body.allowed_to_unprotect = allowed_to_unprotect;
            if (code_owner_approval_required !== undefined)
              body.code_owner_approval_required = code_owner_approval_required;
 
            return gitlab.post(`projects/${encodedProjectId}/protected_branches`, {
              body,
              contentType: "json",
            });
          }
 
          case "unprotect_branch": {
            const { name } = input;
            const encodedName = encodeURIComponent(name);
            await gitlab.delete(`projects/${encodedProjectId}/protected_branches/${encodedName}`);
            return { unprotected: true, name };
          }
 
          case "update_branch_protection": {
            const {
              action: _action,
              project_id: _projectId,
              name,
              allow_force_push,
              allowed_to_push,
              allowed_to_merge,
              allowed_to_unprotect,
              code_owner_approval_required,
            } = input;
 
            const encodedName = encodeURIComponent(name);
            const body: Record<string, unknown> = {};
 
            if (allow_force_push !== undefined) body.allow_force_push = allow_force_push;
            if (allowed_to_push !== undefined) body.allowed_to_push = allowed_to_push;
            if (allowed_to_merge !== undefined) body.allowed_to_merge = allowed_to_merge;
            if (allowed_to_unprotect !== undefined)
              body.allowed_to_unprotect = allowed_to_unprotect;
            if (code_owner_approval_required !== undefined)
              body.code_owner_approval_required = code_owner_approval_required;
 
            return gitlab.patch(`projects/${encodedProjectId}/protected_branches/${encodedName}`, {
              body,
              contentType: "json",
            });
          }
 
          case "create_tag": {
            const { tag_name, ref, message } = input;
            const body: Record<string, unknown> = { tag_name, ref };
 
            if (message !== undefined) body.message = message;
 
            return gitlab.post(`projects/${encodedProjectId}/repository/tags`, {
              body,
              contentType: "json",
            });
          }
 
          case "delete_tag": {
            const { tag_name } = input;
            const encodedTagName = encodeURIComponent(tag_name);
            await gitlab.delete(`projects/${encodedProjectId}/repository/tags/${encodedTagName}`);
            return { deleted: true, tag_name };
          }
 
          case "protect_tag": {
            const {
              action: _action,
              project_id: _projectId,
              name,
              create_access_level,
              allowed_to_create,
            } = input;
 
            const body: Record<string, unknown> = { name };
 
            if (create_access_level !== undefined) body.create_access_level = create_access_level;
            if (allowed_to_create !== undefined) body.allowed_to_create = allowed_to_create;
 
            return gitlab.post(`projects/${encodedProjectId}/protected_tags`, {
              body,
              contentType: "json",
            });
          }
 
          case "unprotect_tag": {
            const { name } = input;
            const encodedName = encodeURIComponent(name);
            await gitlab.delete(`projects/${encodedProjectId}/protected_tags/${encodedName}`);
            return { unprotected: true, name };
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
]);
 
/**
 * Get read-only tool names from the registry
 */
export function getRefsReadOnlyToolNames(): string[] {
  return ["browse_refs"];
}
 
/**
 * Get all tool definitions from the registry
 */
export function getRefsToolDefinitions(): EnhancedToolDefinition[] {
  return Array.from(refsToolRegistry.values());
}
 
/**
 * Get filtered tools based on read-only mode
 */
export function getFilteredRefsTools(readOnlyMode: boolean = false): EnhancedToolDefinition[] {
  if (readOnlyMode) {
    const readOnlyNames = getRefsReadOnlyToolNames();
    return Array.from(refsToolRegistry.values()).filter(tool => readOnlyNames.includes(tool.name));
  }
  return getRefsToolDefinitions();
}