Skip to main content
Glama

collect_code

Aggregate code from a directory or specific files into a single markdown document, streamlining code documentation and review processes.

Instructions

Collect all code from a directory into a single markdown file

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
ignorePatternsNoPatterns to ignore (similar to .gitignore)
inputYes
outputPathYesPath where to save the output markdown file

Implementation Reference

  • Core implementation of the collect_code tool: validates absolute paths, collects files recursively, generates a markdown file with table of contents and code blocks for each file, writes to output path, and returns success message.
    export async function handleCollectCode(options: CodeCollectorOptions): Promise<string> {
      // Проверяем, что все входные пути абсолютные
      const inputs = Array.isArray(options.input) ? options.input : [options.input];
      for (const input of inputs) {
        if (!path.isAbsolute(input)) {
          throw new Error(`Input path must be absolute. Got: ${input}`);
        }
      }
    
      // Проверяем, что выходной путь абсолютный
      if (!path.isAbsolute(options.outputPath)) {
        throw new Error(`Output path must be absolute. Got: ${options.outputPath}`);
      }
    
      // Формируем имя выходного файла
      const date = new Date().toISOString().split('T')[0];
      const inputName = Array.isArray(options.input)
        ? 'MULTIPLE_FILES'
        : path.basename(options.input).toUpperCase();
    
      // Используем предоставленный выходной путь
      const outputPath = options.outputPath;
    
      // Собираем файлы
      const files = await collectFiles(options.input, options.ignorePatterns || []);
    
      if (files.length === 0) {
        return 'No files found matching the criteria';
      }
    
      // Generate markdown content
      const title = Array.isArray(options.input) ? 'Selected Files' : path.basename(options.input);
    
      let markdown = CODE_ANALYSIS_PROMPT;
      markdown += `\n# Code Collection: ${title}\n\n`;
      markdown += `Source: ${
        Array.isArray(options.input) ? options.input.join(', ') : options.input
      }\n\n`;
    
      // Table of contents
      markdown += '## Table of Contents\n\n';
      for (const file of files) {
        const anchor = file.relativePath.toLowerCase().replace(/[^a-z0-9]+/g, '-');
        markdown += `- [${file.relativePath}](#${anchor})\n`;
      }
    
      // File contents
      markdown += '\n## Files\n\n';
      for (const file of files) {
        const anchor = file.relativePath.toLowerCase().replace(/[^a-z0-9]+/g, '-');
        markdown += `### ${file.relativePath} {#${anchor}}\n`;
        markdown += '```' + file.language + '\n';
        markdown += file.content;
        markdown += '\n```\n\n';
      }
    
      // Write output file
      const input = Array.isArray(options.input) ? options.input[0] : options.input;
      await createCodeCollectionFile(input, markdown);
    
      return `Successfully collected ${files.length} files. Output saved to: ${outputPath}`;
    }
  • Input schema for the collect_code tool defining input (string or array of paths), required outputPath (absolute), optional ignorePatterns.
    inputSchema: {
      type: 'object',
      properties: {
        input: {
          oneOf: [
            {
              type: 'string',
              description: 'Path to directory or file to collect code from',
            },
            {
              type: 'array',
              items: {
                type: 'string',
              },
              description: 'List of file paths to collect code from',
            },
          ],
        },
        outputPath: {
          type: 'string',
          description: 'Path where to save the output markdown file',
          pattern: '^/.*',
          examples: ['/path/to/project/src/FULL_CODE_SRC_2024-12-20.md'],
        },
        ignorePatterns: {
          type: 'array',
          items: {
            type: 'string',
          },
          description: 'Patterns to ignore (similar to .gitignore)',
          optional: true,
        },
      },
      required: ['input', 'outputPath'],
    },
  • Registration of the collect_code tool (as codeCollectorTool) in the main tools array exported for the MCP server.
    export const tools = [
      codeCollectorTool,
      installBaseServersTool,
      codeAnalyzerTool,
      githubIssuesTool,
    ];
  • Tool definition and export for collect_code, including name, description, schema, and wrapper handler that invokes the core handleCollectCode.
    export const codeCollectorTool: Tool = {
      name: 'collect_code',
      description: 'Collect all code from a directory into a single markdown file',
      inputSchema: {
        type: 'object',
        properties: {
          input: {
            oneOf: [
              {
                type: 'string',
                description: 'Path to directory or file to collect code from',
              },
              {
                type: 'array',
                items: {
                  type: 'string',
                },
                description: 'List of file paths to collect code from',
              },
            ],
          },
          outputPath: {
            type: 'string',
            description: 'Path where to save the output markdown file',
            pattern: '^/.*',
            examples: ['/path/to/project/src/FULL_CODE_SRC_2024-12-20.md'],
          },
          ignorePatterns: {
            type: 'array',
            items: {
              type: 'string',
            },
            description: 'Patterns to ignore (similar to .gitignore)',
            optional: true,
          },
        },
        required: ['input', 'outputPath'],
      },
      handler: async (args: Record<string, unknown>) => {
        try {
          const input = Array.isArray(args.input) ? args.input.map(String) : String(args.input);
          const outputPath = path.resolve(String(args.outputPath));
    
          const options: CodeCollectorOptions = {
            input,
            outputPath,
            ignorePatterns: args.ignorePatterns as string[] | undefined,
          };
    
          const result = await handleCollectCode(options);
          return {
            content: [
              {
                type: 'text',
                text: result,
              },
            ],
          };
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `Error collecting code: ${error instanceof Error ? error.message : String(error)}`,
              },
            ],
            isError: true,
          };
        }
      },
    };
Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/aindreyway/mcp-neurolora'

If you have feedback or need assistance with the MCP directory API, please join our Discord server