All files / src/entities/core registry.ts

99.46% Statements 186/187
92.12% Branches 117/127
100% Functions 14/14
100% Lines 160/160

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  26x 26x                 26x           26x 26x 26x 26x 26x 26x   26x 26x 26x 26x             26x                               4x 3x 3x 3x               26x                                                                                                 18x   15x   14x                               4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x   4x 1x     3x       4x   4x 4x   4x 4x   4x 1x     3x       6x   6x   6x 6x 6x 6x   6x 6x   6x 1x     5x 5x 2x 2x 1x       4x                                       10x   9x   8x                 8x 8x 8x 8x 8x 8x 8x 8x 8x     8x   4x 4x 4x   4x 1x     3x       4x 4x 4x 4x   4x 1x     3x                                         10x   10x   9x   7x   7x 7x   7x   7x 2x 2x   2x 4x 2x       2x   5x 5x     4x             2x   2x 2x   2x 1x     1x 1x                                       8x   8x   7x   7x 7x     7x   7x 12x 12x       7x 7x   7x 1x     6x 6x                                                                                                                                                           10x   8x   7x   2x 2x   2x 1x     1x 1x       3x 3x   3x 1x     2x       2x 2x   2x 1x     1x 1x                             26x 17x                         26x 8x           26x 7x 4x 4x 36x     3x    
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import * as z from 'zod';
import {
  // Consolidated schemas
  BrowseProjectsSchema,
  BrowseNamespacesSchema,
  BrowseCommitsSchema,
  BrowseEventsSchema,
  BrowseUsersSchema,
  BrowseTodosSchema,
} from './schema-readonly';
import {
  // Consolidated schemas
  ManageProjectSchema,
  ManageNamespaceSchema,
  ManageTodosSchema,
} from './schema';
import { enhancedFetch } from '../../utils/fetch';
import { getGitLabBaseUrl } from '../../utils/gitlab-base-url';
import { normalizeProjectId } from '../../utils/projectIdentifier';
import { encodeApiSegment } from '../../utils/api-path';
import { fetchUsers, smartUserSearch, type UserSearchParams } from '../../utils/smart-user-search';
import { cleanGidsFromObject } from '../../utils/idConversion';
import { ToolRegistry, EnhancedToolDefinition } from '../../types';
import { assertActionAllowed } from '../utils';
import { instanceAtLeast } from '../instance-version';
import { withSafeProjectResponse } from './project-response';
import {
  browseProjects,
  browseNamespaces,
  manageProject,
  manageNamespace,
} from './project-handlers';
 
const CommitDiffsSchema = z.array(
  z.looseObject({
    diff: z.string(),
    old_path: z.string(),
    new_path: z.string(),
    new_file: z.boolean(),
    deleted_file: z.boolean(),
  }),
);
type CommitDiff = z.infer<typeof CommitDiffsSchema>[number];
 
/**
 * Prefix a commit diff with unified-diff file headers, as GitLab's own `unidiff`
 * option does (Gitlab::Git::Diff#unidiff): empty and binary diffs stay as they are.
 */
function withUnifiedHeaders(d: CommitDiff): string {
  if (!d.diff || d.diff.startsWith('Binary files')) return d.diff;
  const oldHeader = d.new_file ? '/dev/null' : `a/${d.old_path}`;
  const newHeader = d.deleted_file ? '/dev/null' : `b/${d.new_path}`;
  return `--- ${oldHeader}\n+++ ${newHeader}\n${d.diff}`;
}
 
/**
 * Core tools registry - CQRS consolidated
 * All tools use discriminated union schema pattern.
 * TypeScript automatically narrows types in each switch case.
 */
export const coreToolRegistry: ToolRegistry = new Map<string, EnhancedToolDefinition>([
  // ============================================================================
  // BROWSE TOOLS (read-only queries)
  // ============================================================================
 
  [
    'browse_projects',
    {
      name: 'browse_projects',
      description:
        'Find, list, or inspect GitLab projects. Actions: search (find by name/topic across GitLab), list (browse accessible projects or group projects), get (retrieve full project details). Related: manage_project to create/update/delete projects.',
      inputSchema: z.toJSONSchema(BrowseProjectsSchema),
      requirements: {
        default: { tier: 'free' },
        // Listing soft-deleted projects needs active admin-mode elevation; the
        // registry strips this parameter when elevation is known inactive (non-admin
        // OR admin role without elevation), and keeps it when elevated or unknown
        // (fail-open). marked_for_deletion_on is a Premium/Ultimate filter (17.1+);
        // the registry strips it on lower tiers/older versions.
        parameters: {
          include_deleted: { requiresAdmin: true },
          marked_for_deletion_on: { tier: 'premium', minVersion: '17.1' },
        },
      },
      handler: withSafeProjectResponse(browseProjects),
    },
  ],
 
  [
    'browse_namespaces',
    {
      name: 'browse_namespaces',
      description:
        'Explore GitLab groups and user namespaces. Actions: list (discover available namespaces), get (retrieve details with storage stats), verify (check if path exists). Related: manage_namespace to create/update/delete groups.',
      inputSchema: z.toJSONSchema(BrowseNamespacesSchema),
      requirements: { default: { tier: 'free' } },
      handler: withSafeProjectResponse(browseNamespaces),
    },
  ],
 
  [
    'browse_commits',
    {
      name: 'browse_commits',
      description:
        'Explore repository commit history and diffs. Actions: list (browse commits with filters), get (retrieve commit metadata and stats), diff (view code changes). Related: browse_refs for branch/tag info.',
      inputSchema: z.toJSONSchema(BrowseCommitsSchema),
      requirements: { default: { tier: 'free' } },
      handler: async (args: unknown): Promise<unknown> => {
        const input = BrowseCommitsSchema.parse(args);
 
        assertActionAllowed('browse_commits', input.action);
 
        switch (input.action) {
          case 'list': {
            const {
              project_id,
              ref_name,
              since,
              until,
              path,
              author,
              all,
              with_stats,
              first_parent,
              order,
              trailers,
              per_page,
              page,
            } = input;
            const queryParams = new URLSearchParams();
 
            if (ref_name) queryParams.set('ref_name', ref_name);
            if (since) queryParams.set('since', since);
            if (until) queryParams.set('until', until);
            if (path) queryParams.set('path', path);
            if (author) queryParams.set('author', author);
            if (all !== undefined) queryParams.set('all', String(all));
            if (with_stats !== undefined) queryParams.set('with_stats', String(with_stats));
            if (first_parent !== undefined) queryParams.set('first_parent', String(first_parent));
            if (order) queryParams.set('order', order);
            if (trailers !== undefined) queryParams.set('trailers', String(trailers));
            Eif (per_page) queryParams.set('per_page', String(per_page));
            if (page) queryParams.set('page', String(page));
 
            const apiUrl = `${getGitLabBaseUrl()}/api/v4/projects/${normalizeProjectId(project_id)}/repository/commits?${queryParams}`;
            const response = await enhancedFetch(apiUrl);
 
            if (!response.ok) {
              throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
            }
 
            return await response.json();
          }
 
          case 'get': {
            const { project_id, sha, stats } = input;
 
            const queryParams = new URLSearchParams();
            if (stats) queryParams.set('stats', 'true');
 
            const apiUrl = `${getGitLabBaseUrl()}/api/v4/projects/${normalizeProjectId(project_id)}/repository/commits/${encodeURIComponent(sha)}?${queryParams}`;
            const response = await enhancedFetch(apiUrl);
 
            if (!response.ok) {
              throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
            }
 
            return await response.json();
          }
 
          case 'diff': {
            const { project_id, sha, unidiff, per_page, page } = input;
            // `unidiff` landed in GitLab 16.5; before that the headers are added here.
            const nativeUnidiff = instanceAtLeast('16.5');
 
            const queryParams = new URLSearchParams();
            if (unidiff && nativeUnidiff) queryParams.set('unidiff', 'true');
            Eif (per_page) queryParams.set('per_page', String(per_page));
            Iif (page) queryParams.set('page', String(page));
 
            const apiUrl = `${getGitLabBaseUrl()}/api/v4/projects/${normalizeProjectId(project_id)}/repository/commits/${encodeURIComponent(sha)}/diff?${queryParams}`;
            const response = await enhancedFetch(apiUrl);
 
            if (!response.ok) {
              throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
            }
 
            const diffs = (await response.json()) as unknown;
            if (!unidiff || nativeUnidiff) return diffs;
            const parsed = CommitDiffsSchema.safeParse(diffs);
            if (!parsed.success) {
              throw new Error(
                `GitLab API error: unexpected commit diff response (${parsed.error.issues[0]?.message ?? 'invalid'})`,
              );
            }
            return parsed.data.map((d) => ({ ...d, diff: withUnifiedHeaders(d) }));
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
 
  [
    'browse_events',
    {
      name: 'browse_events',
      description:
        'Track GitLab activity and events. Actions: user (your activity across all projects), project (specific project activity feed). Filter by date range, action type, or target type.',
      inputSchema: z.toJSONSchema(BrowseEventsSchema),
      requirements: { default: { tier: 'free' } },
      handler: async (args: unknown): Promise<unknown> => {
        const input = BrowseEventsSchema.parse(args);
 
        assertActionAllowed('browse_events', input.action);
 
        const buildQueryParams = (opts: {
          target_type?: string;
          event_action?: string;
          before?: string;
          after?: string;
          sort?: string;
          per_page?: number;
          page?: number;
        }) => {
          const queryParams = new URLSearchParams();
          if (opts.target_type) queryParams.set('target_type', opts.target_type);
          if (opts.event_action) queryParams.set('action', opts.event_action);
          if (opts.before) queryParams.set('before', opts.before);
          if (opts.after) queryParams.set('after', opts.after);
          if (opts.sort) queryParams.set('sort', opts.sort);
          Eif (opts.per_page) queryParams.set('per_page', String(opts.per_page));
          if (opts.page) queryParams.set('page', String(opts.page));
          return queryParams;
        };
 
        switch (input.action) {
          case 'user': {
            const queryParams = buildQueryParams(input);
            const apiUrl = `${getGitLabBaseUrl()}/api/v4/events?${queryParams}`;
            const response = await enhancedFetch(apiUrl);
 
            if (!response.ok) {
              throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
            }
 
            return await response.json();
          }
 
          case 'project': {
            const { project_id } = input;
            const queryParams = buildQueryParams(input);
            const apiUrl = `${getGitLabBaseUrl()}/api/v4/projects/${normalizeProjectId(project_id)}/events?${queryParams}`;
            const response = await enhancedFetch(apiUrl);
 
            if (!response.ok) {
              throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
            }
 
            return await response.json();
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
 
  [
    'browse_users',
    {
      name: 'browse_users',
      description:
        'Find GitLab users with smart pattern detection. Actions: search (find users by name/email/username with transliteration support), get (retrieve specific user by ID). Related: browse_members for project/group membership.',
      inputSchema: z.toJSONSchema(BrowseUsersSchema),
      // User-type filters newer than the floor are emulated on older instances (fetchUsers).
      requirements: { default: { tier: 'free' } },
      handler: async (args: unknown): Promise<unknown> => {
        const input = BrowseUsersSchema.parse(args);
 
        assertActionAllowed('browse_users', input.action);
 
        switch (input.action) {
          case 'search': {
            const { smart_search, search, username, public_email, ...otherParams } = input;
 
            const hasUsernameOrEmail = Boolean(username) || Boolean(public_email);
            const hasOnlySearch = Boolean(search) && !hasUsernameOrEmail;
            const shouldUseSmartSearch =
              smart_search === false ? false : smart_search === true || hasOnlySearch;
 
            if (shouldUseSmartSearch && (search || username || public_email)) {
              const query = search ?? username ?? public_email ?? '';
              const additionalParams: UserSearchParams = {};
 
              Object.entries(otherParams).forEach(([key, value]) => {
                if (value !== undefined && key !== 'smart_search' && key !== 'action') {
                  additionalParams[key] = value;
                }
              });
 
              return await smartUserSearch(query, additionalParams);
            } else {
              const { smart_search: _smart, action: _action, ...params } = input;
              const { users, warning } = await fetchUsers(params);
              // The plain list stays the shape; a filter the instance could only
              // partly apply is reported alongside it.
              return warning
                ? { users: cleanGidsFromObject(users), _warning: warning }
                : cleanGidsFromObject(users);
            }
          }
 
          case 'get': {
            const { user_id } = input;
 
            const apiUrl = `${getGitLabBaseUrl()}/api/v4/users/${encodeURIComponent(user_id)}`;
            const response = await enhancedFetch(apiUrl);
 
            if (!response.ok) {
              throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
            }
 
            const user = await response.json();
            return cleanGidsFromObject(user);
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
 
  [
    'browse_todos',
    {
      name: 'browse_todos',
      description:
        'View your GitLab todo queue (notifications requiring action). Actions: list (filter by state, action type, target type). Todos are auto-created for assignments, mentions, reviews, and pipeline failures. Related: manage_todos to mark done/restore.',
      inputSchema: z.toJSONSchema(BrowseTodosSchema),
      requirements: { default: { tier: 'free' } },
      handler: async (args: unknown): Promise<unknown> => {
        const input = BrowseTodosSchema.parse(args);
 
        assertActionAllowed('browse_todos', input.action);
 
        switch (input.action) {
          case 'list': {
            const queryParams = new URLSearchParams();
            const { action: _action, todo_action, ...rest } = input;
 
            // Map todo_action to API 'action' parameter
            if (todo_action) queryParams.set('action', todo_action);
 
            Object.entries(rest).forEach(([key, value]) => {
              Eif (value !== undefined) {
                queryParams.set(key, String(value));
              }
            });
 
            const apiUrl = `${getGitLabBaseUrl()}/api/v4/todos?${queryParams}`;
            const response = await enhancedFetch(apiUrl);
 
            if (!response.ok) {
              throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
            }
 
            const todos = await response.json();
            return cleanGidsFromObject(todos);
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
 
  // ============================================================================
  // MANAGE TOOLS (write operations)
  // ============================================================================
 
  [
    'manage_project',
    {
      name: 'manage_project',
      description:
        'Create, update, or manage GitLab projects. Actions: create (new project with settings), fork (copy existing project), update (modify settings, including GitLab Duo settings such as automatic Duo code review; any Duo setting GitLab could not apply is listed in not_applied with what it requires), delete (remove permanently), restore (recover a soft-deleted project before purge), archive/unarchive (toggle read-only), transfer (move to different namespace). Related: browse_projects for discovery, including include_deleted to find restorable projects.',
      inputSchema: z.toJSONSchema(ManageProjectSchema),
      requirements: {
        default: { tier: 'free' },
        parameters: {
          issues_template: { tier: 'premium' },
          merge_requests_template: { tier: 'premium' },
          merge_pipelines_enabled: { tier: 'premium' },
          merge_trains_enabled: { tier: 'premium' },
          only_allow_merge_if_all_status_checks_passed: { tier: 'ultimate' },
          requirements_access_level: { tier: 'ultimate' },
          auto_duo_code_review_enabled: { tier: 'premium', minVersion: '18.0' },
          duo_remote_flows_enabled: { tier: 'premium', minVersion: '18.4' },
          duo_sast_fp_detection_enabled: { tier: 'ultimate', minVersion: '18.7' },
          duo_sast_vr_workflow_enabled: { tier: 'ultimate', minVersion: '18.9' },
          duo_secret_detection_fp_enabled: { tier: 'ultimate', minVersion: '18.10' },
          duo_dependency_bump_breaking_changes_enabled: { tier: 'ultimate', minVersion: '19.2' },
        },
      },
      handler: withSafeProjectResponse(manageProject),
    },
  ],
 
  [
    'manage_namespace',
    {
      name: 'manage_namespace',
      description:
        'Create, update, or delete GitLab groups/namespaces. Actions: create (new group with visibility/settings), update (modify group settings, including automatic GitLab Duo code review cascading to subgroups and projects; a Duo setting GitLab could not apply is listed in not_applied with what it requires), delete (remove permanently), restore (recover a soft-deleted group before purge; on GitLab Free needs 18.0+). Related: browse_namespaces for discovery.',
      inputSchema: z.toJSONSchema(ManageNamespaceSchema),
      requirements: {
        default: { tier: 'free' },
        parameters: {
          membership_lock: { tier: 'premium' },
          wiki_access_level: { tier: 'premium' },
          ip_restriction_ranges: { tier: 'premium' },
          allowed_email_domains_list: { tier: 'premium', minVersion: '17.4' },
          unique_project_download_limit: { tier: 'ultimate' },
          auto_duo_code_review_enabled: { tier: 'premium', minVersion: '18.7' },
        },
      },
      handler: withSafeProjectResponse(manageNamespace),
    },
  ],
 
  // ============================================================================
  // TODOS TOOLS
  // ============================================================================
 
  [
    'manage_todos',
    {
      name: 'manage_todos',
      description:
        'Manage your GitLab todo queue. Actions: mark_done (complete a single todo), mark_all_done (clear entire queue), restore (undo completion). Related: browse_todos to view your todo list.',
      inputSchema: z.toJSONSchema(ManageTodosSchema),
      requirements: { default: { tier: 'free' } },
      handler: async (args: unknown): Promise<unknown> => {
        const input = ManageTodosSchema.parse(args);
 
        assertActionAllowed('manage_todos', input.action);
 
        switch (input.action) {
          case 'mark_done': {
            const apiUrl = `${getGitLabBaseUrl()}/api/v4/todos/${encodeApiSegment(input.id)}/mark_as_done`;
            const response = await enhancedFetch(apiUrl, { method: 'POST' });
 
            if (!response.ok) {
              throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
            }
 
            const todo = await response.json();
            return cleanGidsFromObject(todo);
          }
 
          case 'mark_all_done': {
            const apiUrl = `${getGitLabBaseUrl()}/api/v4/todos/mark_all_as_done`;
            const response = await enhancedFetch(apiUrl, { method: 'POST' });
 
            if (!response.ok) {
              throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
            }
 
            return { success: true, message: 'All todos marked as done' };
          }
 
          case 'restore': {
            const apiUrl = `${getGitLabBaseUrl()}/api/v4/todos/${encodeApiSegment(input.id)}/mark_as_pending`;
            const response = await enhancedFetch(apiUrl, { method: 'POST' });
 
            if (!response.ok) {
              throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
            }
 
            const todo = await response.json();
            return cleanGidsFromObject(todo);
          }
 
          /* 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 getCoreReadOnlyToolNames(): string[] {
  return [
    'browse_projects',
    'browse_namespaces',
    'browse_commits',
    'browse_events',
    'browse_users',
    'browse_todos',
  ];
}
 
/**
 * Get all tool definitions from the registry
 */
export function getCoreToolDefinitions(): EnhancedToolDefinition[] {
  return Array.from(coreToolRegistry.values());
}
 
/**
 * Get filtered tools based on read-only mode
 */
export function getFilteredCoreTools(readOnlyMode: boolean = false): EnhancedToolDefinition[] {
  if (readOnlyMode) {
    const readOnlyNames = getCoreReadOnlyToolNames();
    return Array.from(coreToolRegistry.values()).filter((tool) =>
      readOnlyNames.includes(tool.name),
    );
  }
  return getCoreToolDefinitions();
}