Skip to main content
Glama

format_code

Formats code files according to a chosen style guide like Prettier or ESLint, with options for automatic fixing and custom configurations.

Instructions

Format code using specified style guide

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesPath to the file to format
styleNoCode style guide to use (e.g., prettier, eslint)prettier
configNoConfiguration options for the formatter
fixNoWhether to fix issues automatically

Implementation Reference

  • The executeCommand method that calls codeService.formatCode() to format the file at the given path, and returns the result with success/error messaging.
      protected async executeCommand(context: CommandContext): Promise<CommandResult> {
        try {
          const codeService = context.container.getService<CodeAnalysisService>('codeAnalysisService');
          const result = await codeService.formatCode(
            context.args.path,
            {
              style: context.args.style,
              config: context.args.config,
              fix: context.args.fix
            }
          );
    
          return {
            content: [{
              type: 'text',
              text: JSON.stringify({
                message: result.modified ? 'Code formatted successfully' : 'Code is already properly formatted',
                path: context.args.path,
                style: context.args.style,
                modified: result.modified,
                changes: result.changes
              }, null, 2)
            }]
          };
        } catch (error) {
          return {
            content: [{
              type: 'text',
              text: `Failed to format code: ${error instanceof Error ? error.message : String(error)}`
            }]
          };
        }
      }
    }
  • The core formatCode implementation: reads the file, parses it with Babel, regenerates it, compares, and optionally writes changes back to disk.
    async formatCode(
      path: string,
      options?: {
        style?: 'prettier' | 'eslint' | 'standard' | 'custom';
        config?: Record<string, any>;
        fix?: boolean;
      }
    ): Promise<{
      modified: boolean;
      changes: Array<{ line: number; description: string }>;
    }> {
      const originalContent = await fs.readFile(path, 'utf-8');
      const changes: Array<{ line: number; description: string }> = [];
      
      // For now, just re-parse and regenerate to normalize the code
      const ast = parser.parse(originalContent, {
        sourceType: 'module',
        plugins: ['jsx', 'typescript', 'decorators-legacy']
      });
    
      const output = generate(ast, {
        retainLines: false,
        compact: false,
        concise: false,
        comments: true
      });
    
      const modified = originalContent !== output.code;
      
      if (modified && options?.fix !== false) {
        await fs.writeFile(path, output.code);
        
        // Simple line-by-line comparison for changes
        const oldLines = originalContent.split('\n');
        const newLines = output.code.split('\n');
        
        for (let i = 0; i < Math.max(oldLines.length, newLines.length); i++) {
          if (oldLines[i] !== newLines[i]) {
            changes.push({
              line: i + 1,
              description: 'Line formatted'
            });
          }
        }
      }
      
      return {
        modified,
        changes
      };
    }
  • Input schema definition (inputSchema and FormatCodeArgsSchema) specifying path (required), style, config, and fix parameters for the format_code tool.
    const FormatCodeArgsSchema = {
        type: 'object',
        properties: {
          path: {
            type: 'string',
            description: 'Path to the file to format'
          },
          style: {
            type: 'string',
            description: 'Code style guide to use (e.g., prettier, eslint)',
            default: 'prettier'
          },
          config: {
            type: 'object',
            description: 'Configuration options for the formatter',
            additionalProperties: true
          },
          fix: {
            type: 'boolean',
            description: 'Whether to fix issues automatically',
            default: true
          }
        },
        required: ['path']
      };
    
    
    export class FormatCodeCommand extends BaseCommand {
      readonly name = 'format_code';
      readonly description = 'Format code using specified style guide';
      readonly inputSchema = {
        type: 'object',
        properties: {
          path: {
            type: 'string',
            description: 'Path to the file to format'
          },
          style: {
            type: 'string',
            description: 'Code style guide to use (e.g., prettier, eslint)',
            default: 'prettier'
          },
          config: {
            type: 'object',
            description: 'Configuration options for the formatter',
            additionalProperties: true
          },
          fix: {
            type: 'boolean',
            description: 'Whether to fix issues automatically',
            default: true
          }
        },
        required: ['path'],
        additionalProperties: false
      };
  • Interface definition for the formatCode method, specifying the path and optional style/config/fix parameters and the return type.
      formatCode(
        path: string,
        options?: {
          style?: 'prettier' | 'eslint' | 'standard' | 'custom';
          config?: Record<string, any>;
          fix?: boolean;
        }
      ): Promise<{
        modified: boolean;
        changes: Array<{ line: number; description: string }>;
      }>;
      analyzeQuality(path: string): Promise<any>;
    }
  • Registration of FormatCodeCommand: imported from the code module (line 121) and registered with the registry (line 146).
    const codeModule = await import('../implementations/code/index.js');
    if (this.enableDebugLogs) {
      console.log('Code commands available:', Object.keys(codeModule));
    }
    const { AnalyzeCodeCommand, ModifyCodeCommand, SuggestRefactoringCommand, FormatCodeCommand } = codeModule;
    
    // Register git commands
    this.registry.register(new GitInitCommand());
    this.registry.register(new GitAddCommand());
    this.registry.register(new GitCommitCommand());
    this.registry.register(new GitPushCommand());
    this.registry.register(new GitPullCommand());
    this.registry.register(new GitBranchCommand());
    this.registry.register(new GitCheckoutCommand());
    this.registry.register(new GitLogCommand());
    this.registry.register(new GitCloneCommand());
    this.registry.register(new GitHubCreatePRCommand());
    this.registry.register(new GitStatusCommand());
    
    // Register search commands
    this.registry.register(new SearchFilesCommand());
    this.registry.register(new SearchContentCommand());
    this.registry.register(new FuzzySearchCommand());
    this.registry.register(new SemanticSearchCommand());
    
    // Register code commands
    this.registry.register(new AnalyzeCodeCommand());
    this.registry.register(new ModifyCodeCommand());
    this.registry.register(new SuggestRefactoringCommand());
    this.registry.register(new FormatCodeCommand());
Behavior2/5

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

No annotations are provided, so the description must cover behavioral traits. It only says 'format code' but omits details like whether it overwrites the file, handles errors, or requires specific permissions.

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?

Single sentence, no redundant information, and front-loaded with the core purpose.

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?

No output schema and no annotations. With 4 parameters including a nested object, the description lacks details on return value, side effects, or error behavior, making it incomplete for confident invocation.

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?

Schema coverage is 100% with all parameters described. The description adds no value beyond the schema, so baseline score 3 is appropriate.

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

Purpose5/5

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

The description clearly states the tool formats code using a specified style guide, which distinguishes it from siblings like 'modify_code' or 'analyze_code' that have 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?

No guidance on when to use this tool vs alternatives such as 'modify_code' or 'suggest_refactoring'. The agent must infer context from sibling names.

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

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/proofmath-owner/ai-filesystem-mcp'

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