All files / src/entities/files registry.ts

97.61% Statements 82/84
88.88% Branches 32/36
100% Functions 13/13
97.53% Lines 79/81

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  3x 3x 3x 3x 3x 3x           3x                   4x 4x   4x 4x 8x 4x       4x 4x           4x 2x     2x 2x                       4x 3x   3x 3x 1x     3x 3x           3x 1x       2x     2x                                     4x 4x   4x 4x 24x 16x       4x 4x                 3x 1x     2x 2x                       3x 3x     3x               3x                   3x 18x 6x       3x 3x                 3x       2x 2x                       2x 2x     2x       2x   2x 2x 2x 79x   2x         2x   2x 2x               2x 1x     1x 1x                 3x 13x           3x 2x           3x 3x 2x 10x   1x    
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { zodToJsonSchema } from "zod-to-json-schema";
import { GetRepositoryTreeSchema, GetFileContentsSchema } from "./schema-readonly";
import { CreateOrUpdateFileSchema, PushFilesSchema, MarkdownUploadSchema } from "./schema";
import { enhancedFetch } from "../../utils/fetch";
import { normalizeProjectId } from "../../utils/projectIdentifier";
import { cleanGidsFromObject } from "../../utils/idConversion";
import { ToolRegistry, EnhancedToolDefinition } from "../../types";
 
/**
 * Files tools registry - unified registry containing all file operation tools with their handlers
 */
export const filesToolRegistry: ToolRegistry = new Map<string, EnhancedToolDefinition>([
  // Read-only tools
  [
    "get_repository_tree",
    {
      name: "get_repository_tree",
      description:
        "BROWSE: List files/folders WITHOUT reading content. Use when: Exploring project structure, Finding file locations, Checking what exists. Returns: names, types (blob=file, tree=folder), sizes. Set recursive=true for full tree. Does NOT return file contents! See also: get_file_contents to READ actual content.",
      inputSchema: zodToJsonSchema(GetRepositoryTreeSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = GetRepositoryTreeSchema.parse(args);
        const { project_id } = options;
 
        const queryParams = new URLSearchParams();
        Object.entries(options).forEach(([key, value]) => {
          if (value !== undefined && key !== "project_id") {
            queryParams.set(key, String(value));
          }
        });
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${normalizeProjectId(project_id)}/repository/tree?${queryParams}`;
        const response = await enhancedFetch(apiUrl, {
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
          },
        });
 
        if (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const tree = await response.json();
        return cleanGidsFromObject(tree);
      },
    },
  ],
  [
    "get_file_contents",
    {
      name: "get_file_contents",
      description:
        "READ: Get actual file content from repository. Use when: Reading source code, Viewing configs/docs, Getting file data. Returns base64-encoded content (decode required!) plus metadata. For browsing structure use get_repository_tree instead. Supports any branch/tag/commit via ref param.",
      inputSchema: zodToJsonSchema(GetFileContentsSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = GetFileContentsSchema.parse(args);
        const { project_id, file_path, ref } = options;
 
        const queryParams = new URLSearchParams();
        if (ref) {
          queryParams.set("ref", ref);
        }
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${normalizeProjectId(project_id)}/repository/files/${encodeURIComponent(file_path)}/raw?${queryParams}`;
        const response = await enhancedFetch(apiUrl, {
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
          },
        });
 
        if (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        // Raw endpoint returns the file content directly, not JSON
        const content = await response.text();
 
        // Return structured response with file metadata
        return {
          file_path: file_path,
          ref: ref ?? "HEAD",
          size: content.length,
          content: content,
          content_type: response.headers.get("content-type") ?? "text/plain",
        };
      },
    },
  ],
  // Write tools
  [
    "create_or_update_file",
    {
      name: "create_or_update_file",
      description:
        "SINGLE FILE: Create new OR update existing file in one commit. Use when: Changing ONE file only, Quick edits, Adding single document. Auto-detects create vs update. Content must be base64-encoded! For multiple files use push_files instead. Creates commit with your message.",
      inputSchema: zodToJsonSchema(CreateOrUpdateFileSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = CreateOrUpdateFileSchema.parse(args);
        const { project_id, file_path } = options;
 
        const body = new URLSearchParams();
        Object.entries(options).forEach(([key, value]) => {
          if (value !== undefined && key !== "project_id" && key !== "file_path") {
            body.set(key, String(value));
          }
        });
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${normalizeProjectId(project_id)}/repository/files/${encodeURIComponent(file_path)}`;
        const response = await enhancedFetch(apiUrl, {
          method: "POST",
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
            "Content-Type": "application/x-www-form-urlencoded",
          },
          body: body.toString(),
        });
 
        if (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const result = await response.json();
        return cleanGidsFromObject(result);
      },
    },
  ],
  [
    "push_files",
    {
      name: "push_files",
      description:
        "BATCH: Commit MULTIPLE file changes atomically. Use when: Changing 2+ files together, Refactoring across files, Coordinated updates. More efficient than multiple single commits. Supports: create/update/delete/move operations. All changes in ONE commit. For single file use create_or_update_file.",
      inputSchema: zodToJsonSchema(PushFilesSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = PushFilesSchema.parse(args);
        const { project_id } = options;
 
        // Convert files to actions format for GitLab API
        const actions = options.files.map(file => ({
          action: "create",
          file_path: file.file_path,
          content: file.content,
          encoding: file.encoding ?? "text",
          execute_filemode: file.execute_filemode ?? false,
        }));
 
        const body = {
          branch: options.branch,
          commit_message: options.commit_message,
          actions: actions,
          start_branch: options.start_branch,
          author_email: options.author_email,
          author_name: options.author_name,
        };
 
        // Remove undefined fields
        Object.keys(body).forEach(key => {
          if (body[key as keyof typeof body] === undefined) {
            delete body[key as keyof typeof body];
          }
        });
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${normalizeProjectId(project_id)}/repository/commits`;
        const response = await enhancedFetch(apiUrl, {
          method: "POST",
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify(body),
        });
 
        Iif (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const commit = await response.json();
        return cleanGidsFromObject(commit);
      },
    },
  ],
  [
    "upload_markdown",
    {
      name: "upload_markdown",
      description:
        "UPLOAD ASSET: Add images/docs for markdown embedding. Use when: Adding screenshots to issues/MRs, Uploading diagrams for wikis, Attaching files to documentation. Returns markdown-ready URL like ![](url). Stored in uploads, NOT repository. Supports: images, PDFs, any binary files.",
      inputSchema: zodToJsonSchema(MarkdownUploadSchema),
      handler: async (args: unknown): Promise<unknown> => {
        const options = MarkdownUploadSchema.parse(args);
        const { project_id, file, filename } = options;
 
        // Create FormData for file upload
        const formData = new FormData();
 
        // Convert base64 file content to blob if needed
        let fileBlob: Blob;
        if (typeof file === "string") {
          // Assume it's base64 encoded
          const binaryString = Buffer.from(file, "base64").toString("binary");
          const bytes = new Uint8Array(binaryString.length);
          for (let i = 0; i < binaryString.length; i++) {
            bytes[i] = binaryString.charCodeAt(i);
          }
          fileBlob = new Blob([bytes]);
        } else E{
          fileBlob = file as Blob;
        }
 
        formData.append("file", fileBlob, filename);
 
        const apiUrl = `${process.env.GITLAB_API_URL}/api/v4/projects/${normalizeProjectId(project_id)}/uploads`;
        const response = await enhancedFetch(apiUrl, {
          method: "POST",
          headers: {
            Authorization: `Bearer ${process.env.GITLAB_TOKEN}`,
          },
          body: formData,
        });
 
        if (!response.ok) {
          throw new Error(`GitLab API error: ${response.status} ${response.statusText}`);
        }
 
        const upload = await response.json();
        return cleanGidsFromObject(upload);
      },
    },
  ],
]);
 
/**
 * Get read-only tool names from the registry
 */
export function getFilesReadOnlyToolNames(): string[] {
  return ["get_repository_tree", "get_file_contents"];
}
 
/**
 * Get all tool definitions from the registry (for backward compatibility)
 */
export function getFilesToolDefinitions(): EnhancedToolDefinition[] {
  return Array.from(filesToolRegistry.values());
}
 
/**
 * Get filtered tools based on read-only mode
 */
export function getFilteredFilesTools(readOnlyMode: boolean = false): EnhancedToolDefinition[] {
  if (readOnlyMode) {
    const readOnlyNames = getFilesReadOnlyToolNames();
    return Array.from(filesToolRegistry.values()).filter(tool => readOnlyNames.includes(tool.name));
  }
  return getFilesToolDefinitions();
}