All files / src/entities/webhooks registry.ts

91.07% Statements 51/56
75.75% Branches 25/33
100% Functions 9/9
91.07% Lines 51/56

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 19316x 16x 16x 16x   16x               16x                           4x     4x         4x 4x 2x 2x 1x   1x     4x     3x             2x 2x             1x 1x                                               6x     4x         4x 4x 4x               4x 2x 2x 10x       3x     2x     4x     1x   1x               1x   1x               1x   1x 1x         1x   1x                                   16x 10x           16x 4x           16x 2x 1x 1x 2x     1x    
import * as z from "zod";
import { BrowseWebhooksSchema } from "./schema-readonly";
import { ManageWebhookSchema } from "./schema";
import { gitlab, toQuery } from "../../utils/gitlab-api";
import { ToolRegistry, EnhancedToolDefinition } from "../../types";
import { isActionDenied } from "../../config";
 
/**
 * Webhooks tools registry - 2 CQRS tools (discriminated union schema)
 *
 * browse_webhooks (Query): list, get
 * manage_webhook (Command): create, update, delete, test
 */
export const webhooksToolRegistry: ToolRegistry = new Map<string, EnhancedToolDefinition>([
  // ============================================================================
  // browse_webhooks - CQRS Query Tool (discriminated union schema)
  // TypeScript automatically narrows types in each switch case
  // ============================================================================
  [
    "browse_webhooks",
    {
      name: "browse_webhooks",
      description:
        "List and inspect webhook configurations for projects or groups. Actions: list (all webhooks with event types and status), get (webhook details by ID). Related: manage_webhook to create/update/delete/test.",
      inputSchema: z.toJSONSchema(BrowseWebhooksSchema),
      gate: { envVar: "USE_WEBHOOKS", defaultValue: true },
      handler: async (args: unknown) => {
        const input = BrowseWebhooksSchema.parse(args);
 
        // Runtime validation: reject denied actions even if they bypass schema filtering
        Iif (isActionDenied("browse_webhooks", input.action)) {
          throw new Error(`Action '${input.action}' is not allowed for browse_webhooks tool`);
        }
 
        // Helper to determine base API path from scope
        const getBasePath = (scope: "project" | "group", projectId?: string, groupId?: string) => {
          if (scope === "project" && projectId) {
            return `projects/${encodeURIComponent(projectId)}/hooks`;
          } else if (scope === "group" && groupId) {
            return `groups/${encodeURIComponent(groupId)}/hooks`;
          }
          throw new Error("Invalid scope or missing project/group ID");
        };
 
        switch (input.action) {
          case "list": {
            // TypeScript knows: input has scope, projectId/groupId, per_page, page
            const basePath = getBasePath(input.scope, input.projectId, input.groupId);
            const {
              action: _action,
              scope: _scope,
              projectId: _pid,
              groupId: _gid,
              ...queryParams
            } = input;
            return gitlab.get(basePath, {
              query: toQuery(queryParams, []),
            });
          }
 
          case "get": {
            // TypeScript knows: input has scope, projectId/groupId, hookId
            const basePath = getBasePath(input.scope, input.projectId, input.groupId);
            return gitlab.get(`${basePath}/${input.hookId}`);
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
 
  // ============================================================================
  // manage_webhook - CQRS Command Tool (discriminated union schema)
  // TypeScript automatically narrows types in each switch case
  // ============================================================================
  [
    "manage_webhook",
    {
      name: "manage_webhook",
      description:
        "Create, update, delete, or test webhooks for event-driven automation. Actions: create (URL + event types + optional secret), update (modify settings), delete (remove), test (trigger delivery for specific event). Related: browse_webhooks for inspection.",
      inputSchema: z.toJSONSchema(ManageWebhookSchema),
      gate: { envVar: "USE_WEBHOOKS", defaultValue: true },
      handler: async (args: unknown) => {
        const input = ManageWebhookSchema.parse(args);
 
        // Runtime validation: reject denied actions even if they bypass schema filtering
        Iif (isActionDenied("manage_webhook", input.action)) {
          throw new Error(`Action '${input.action}' is not allowed for manage_webhook tool`);
        }
 
        // Determine base path from scope and IDs
        const getBasePath = (scope: "project" | "group", projectId?: string, groupId?: string) => {
          if (scope === "project" && projectId) {
            return `projects/${encodeURIComponent(projectId)}/hooks`;
          } else Eif (scope === "group" && groupId) {
            return `groups/${encodeURIComponent(groupId)}/hooks`;
          }
          throw new Error("Invalid scope or missing project/group ID");
        };
 
        // Helper to filter webhook data for API requests
        const buildRequestBody = (data: Record<string, unknown>): Record<string, unknown> => {
          const body: Record<string, unknown> = {};
          for (const [key, value] of Object.entries(data)) {
            if (
              value !== undefined &&
              !["action", "scope", "projectId", "groupId", "hookId", "trigger"].includes(key)
            ) {
              body[key] = value;
            }
          }
          return body;
        };
 
        switch (input.action) {
          case "create": {
            // TypeScript knows: input has url (required), scope, projectId/groupId, event fields
            const basePath = getBasePath(input.scope, input.projectId, input.groupId);
 
            return gitlab.post(basePath, {
              body: buildRequestBody(input),
              contentType: "json",
            });
          }
 
          case "update": {
            // TypeScript knows: input has hookId (required), scope, projectId/groupId, optional fields
            const basePath = getBasePath(input.scope, input.projectId, input.groupId);
 
            return gitlab.put(`${basePath}/${input.hookId}`, {
              body: buildRequestBody(input),
              contentType: "json",
            });
          }
 
          case "delete": {
            // TypeScript knows: input has hookId (required), scope, projectId/groupId
            const basePath = getBasePath(input.scope, input.projectId, input.groupId);
 
            await gitlab.delete(`${basePath}/${input.hookId}`);
            return { success: true, message: "Webhook deleted successfully" };
          }
 
          case "test": {
            // TypeScript knows: input has hookId (required), trigger (required), scope, projectId/groupId
            const basePath = getBasePath(input.scope, input.projectId, input.groupId);
 
            return gitlab.post(`${basePath}/${input.hookId}/test/${input.trigger}`, {
              contentType: "json",
            });
          }
 
          /* 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.
 * Only browse_webhooks is read-only. manage_webhook is purely write operations.
 */
export function getWebhooksReadOnlyToolNames(): string[] {
  return ["browse_webhooks"];
}
 
/**
 * Get all tool definitions from the registry
 */
export function getWebhooksToolDefinitions(): EnhancedToolDefinition[] {
  return Array.from(webhooksToolRegistry.values());
}
 
/**
 * Get filtered tools based on read-only mode
 */
export function getFilteredWebhooksTools(readOnlyMode: boolean = false): EnhancedToolDefinition[] {
  if (readOnlyMode) {
    const readOnlyNames = getWebhooksReadOnlyToolNames();
    return Array.from(webhooksToolRegistry.values()).filter(tool =>
      readOnlyNames.includes(tool.name)
    );
  }
  return getWebhooksToolDefinitions();
}