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,
          };
        }
      },
    };
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions the action ('collect') and output format ('markdown file'), but fails to detail critical behaviors like whether it overwrites existing files, handles errors (e.g., missing directories), requires specific permissions, or includes metadata in the output. This leaves significant gaps for a tool that modifies files.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that front-loads the core purpose without unnecessary details. It uses clear language ('collect all code', 'single markdown file') and avoids redundancy, making it easy to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (file system operations, output generation) and lack of annotations or output schema, the description is incomplete. It doesn't cover behavioral aspects like error handling, file overwriting, or output structure, which are crucial for safe and effective use. This inadequacy is notable for a tool that creates files.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description adds minimal parameter semantics beyond the schema, which has 67% coverage. It implies 'input' is for source paths and 'outputPath' for the markdown file, but doesn't explain the dual nature of 'input' (directory vs. list) or how 'ignorePatterns' functions in practice. With moderate schema coverage, the baseline is 3, as the description doesn't fully compensate for the gaps.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('collect all code') and the output ('into a single markdown file'), specifying both verb and resource. However, it doesn't explicitly differentiate from sibling tools like 'analyze_code' or 'create_github_issues', which might involve code handling but serve different purposes.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives like 'analyze_code' for code analysis or 'create_github_issues' for issue tracking. It lacks context about prerequisites, such as needing access to the directory, or exclusions, like not being suitable for real-time code processing.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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