All files / src/entities/labels registry.ts

94.59% Statements 35/37
78.57% Branches 11/14
100% Functions 6/6
94.59% Lines 35/37

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 16214x 14x 14x 14x 14x   14x               14x                           14x     10x       10x   10x     6x 6x   6x         4x       4x                                                     17x     11x       11x   11x     4x                                     4x   4x               3x     2x                             14x 14x           14x 7x           14x 6x 4x 4x 8x     2x    
import * as z from "zod";
import { BrowseLabelsSchema } from "./schema-readonly";
import { ManageLabelSchema } from "./schema";
import { gitlab, toQuery } from "../../utils/gitlab-api";
import { resolveNamespaceForAPI } from "../../utils/namespace";
import { ToolRegistry, EnhancedToolDefinition } from "../../types";
import { isActionDenied } from "../../config";
 
/**
 * Labels tools registry - 2 CQRS tools replacing 5 individual tools
 *
 * browse_labels (Query): list, get
 * manage_label (Command): create, update, delete
 */
export const labelsToolRegistry: ToolRegistry = new Map<string, EnhancedToolDefinition>([
  // ============================================================================
  // browse_labels - CQRS Query Tool (discriminated union schema)
  // TypeScript automatically narrows types in each switch case
  // ============================================================================
  [
    "browse_labels",
    {
      name: "browse_labels",
      description:
        "List and inspect project or group labels. Actions: list (all labels with search filtering), get (single label by ID or name). Related: manage_label to create/update/delete.",
      inputSchema: z.toJSONSchema(BrowseLabelsSchema),
      gate: { envVar: "USE_LABELS", defaultValue: true },
      handler: async (args: unknown) => {
        const input = BrowseLabelsSchema.parse(args);
 
        // Runtime validation: reject denied actions even if they bypass schema filtering
        Iif (isActionDenied("browse_labels", input.action)) {
          throw new Error(`Action '${input.action}' is not allowed for browse_labels tool`);
        }
 
        const { entityType, encodedPath } = await resolveNamespaceForAPI(input.namespace);
 
        switch (input.action) {
          case "list": {
            // TypeScript knows: input has search, with_counts, include_ancestor_groups, per_page, page (optional)
            const { action: _action, namespace: _namespace, ...rest } = input;
            const query = toQuery(rest, []);
 
            return gitlab.get(`${entityType}/${encodedPath}/labels`, { query });
          }
 
          case "get": {
            // TypeScript knows: input has label_id (required), include_ancestor_groups (optional)
            const query = input.include_ancestor_groups
              ? toQuery({ include_ancestor_groups: input.include_ancestor_groups }, [])
              : undefined;
 
            return gitlab.get(
              `${entityType}/${encodedPath}/labels/${encodeURIComponent(input.label_id)}`,
              { query }
            );
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
 
  // ============================================================================
  // manage_label - CQRS Command Tool (discriminated union schema)
  // TypeScript automatically narrows types in each switch case
  // ============================================================================
  [
    "manage_label",
    {
      name: "manage_label",
      description:
        "Create, update, or delete project/group labels. Actions: create (name + hex color required), update (modify properties), delete (remove permanently). Related: browse_labels for discovery.",
      inputSchema: z.toJSONSchema(ManageLabelSchema),
      gate: { envVar: "USE_LABELS", defaultValue: true },
      handler: async (args: unknown) => {
        const input = ManageLabelSchema.parse(args);
 
        // Runtime validation: reject denied actions even if they bypass schema filtering
        Iif (isActionDenied("manage_label", input.action)) {
          throw new Error(`Action '${input.action}' is not allowed for manage_label tool`);
        }
 
        const { entityType, encodedPath } = await resolveNamespaceForAPI(input.namespace);
 
        switch (input.action) {
          case "create": {
            // TypeScript knows: input has name, color (required), description, priority (optional)
            return gitlab.post(`${entityType}/${encodedPath}/labels`, {
              body: {
                name: input.name,
                color: input.color,
                description: input.description,
                priority: input.priority,
              },
              contentType: "json",
            });
          }
 
          case "update": {
            // TypeScript knows: input has label_id (required), name, new_name, color, description, priority (optional)
            const {
              action: _action,
              namespace: _namespace,
              label_id,
              name: _name,
              ...body
            } = input;
 
            return gitlab.put(
              `${entityType}/${encodedPath}/labels/${encodeURIComponent(label_id)}`,
              { body, contentType: "json" }
            );
          }
 
          case "delete": {
            // TypeScript knows: input has label_id (required)
            await gitlab.delete(
              `${entityType}/${encodedPath}/labels/${encodeURIComponent(input.label_id)}`
            );
            return { deleted: true };
          }
 
          /* 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 getLabelsReadOnlyToolNames(): string[] {
  return ["browse_labels"];
}
 
/**
 * Get all tool definitions from the registry
 */
export function getLabelsToolDefinitions(): EnhancedToolDefinition[] {
  return Array.from(labelsToolRegistry.values());
}
 
/**
 * Get filtered tools based on read-only mode
 */
export function getFilteredLabelsTools(readOnlyMode: boolean = false): EnhancedToolDefinition[] {
  if (readOnlyMode) {
    const readOnlyNames = getLabelsReadOnlyToolNames();
    return Array.from(labelsToolRegistry.values()).filter(tool =>
      readOnlyNames.includes(tool.name)
    );
  }
  return getLabelsToolDefinitions();
}