Skip to main content
Glama

validate_code

Check code syntax and formatting using linters like Prettier to identify errors before finalizing your code.

Instructions

Validates code syntax and formatting using available linters (e.g., Prettier). usage: providing code snippets to check for correctness before finalizing.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesThe code content to validate.
languageYesThe programming language (e.g., 'typescript', 'python', 'json').

Implementation Reference

  • The core handler function that executes the validate_code tool logic: writes code to temp file, runs Prettier check for JS/TS/etc., Python py_compile for Python, or warns for unsupported languages.
    export async function validateCodeHandler(args: any) {
        const { code, language } = args;
    
        // Create a temporary file to run validation against
        const tmpDir = os.tmpdir();
        const fileName = `validate_${Date.now()}.${getExt(language)}`;
        const filePath = path.join(tmpDir, fileName);
    
        try {
            await fs.writeFile(filePath, code);
    
            // Default to Prettier for supported languages
            if (["javascript", "typescript", "json", "css", "html", "markdown", "yaml"].includes(language)) {
                try {
                    // Check syntax and formatting
                    await execAsync(`npx prettier --check "${filePath}"`);
                    // If checking passed, it's valid code (mostly)
                    return {
                        content: [{ type: "text", text: "✅ Code is valid and formatted correctly." }]
                    };
                } catch (error: any) {
                    // Prettier error output usually contains the syntax error details
                    return {
                        content: [{ type: "text", text: `❌ Validation Failed:\n${error.stdout || error.stderr || error.message}` }]
                    };
                }
            }
    
            // Fallback for other languages (mock validation for now, or add specific compilers like `python -m py_compile`)
            if (language === "python") {
                try {
                    await execAsync(`python -m py_compile "${filePath}"`);
                    return { content: [{ type: "text", text: "✅ Python syntax is valid." }] };
                } catch (error: any) {
                    return { content: [{ type: "text", text: `❌ Python Syntax Error:\n${error.stderr}` }] };
                }
            }
    
            return {
                content: [{ type: "text", text: `⚠️ No specific validator configured for ${language}, but code was received.` }]
            };
    
        } catch (err: any) {
            return {
                content: [{ type: "text", text: `System Error during validation: ${err.message}` }]
            };
        } finally {
            // Cleanup
            try { await fs.unlink(filePath); } catch { }
        }
    }
  • Zod schema definition for the validate_code tool, specifying input parameters: code (string) and language (string).
    export const validateCodeSchema = {
        name: "validate_code",
        description: "Validates code syntax and formatting using available linters (e.g., Prettier). usage: providing code snippets to check for correctness before finalizing.",
        inputSchema: z.object({
            code: z.string().describe("The code content to validate."),
            language: z.string().describe("The programming language (e.g., 'typescript', 'python', 'json')."),
        })
    };
  • src/index.ts:94-94 (registration)
    Registration of the validate_code tool in the main toolRegistry Map used by the stdio MCP server.
    ["validate_code", { schema: validateCodeSchema, handler: validateCodeHandler }],
  • src/server.ts:102-102 (registration)
    Registration of the validate_code tool in the toolRegistry Map used by the HTTP MCP server.
    ["validate_code", { schema: validateCodeSchema, handler: validateCodeHandler }],
  • Helper function to determine file extension based on programming language, used for creating temporary files for validation.
    function getExt(lang: string): string {
        const map: Record<string, string> = {
            typescript: "ts", javascript: "js", python: "py", rust: "rs", go: "go",
            html: "html", css: "css", json: "json"
        };
        return map[lang] || "txt";
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. While it mentions the tool validates syntax and formatting using linters, it doesn't describe what happens during validation (e.g., error reporting, warnings, success/failure states), whether it's read-only or has side effects, or any performance or rate limit considerations. This leaves significant gaps for a tool with no annotation coverage.

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

Conciseness4/5

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

The description is concise with two sentences that efficiently convey the tool's purpose and usage. It's front-loaded with the core functionality, though the second sentence could be slightly more structured (e.g., 'Usage: Provide code snippets to check for correctness before finalizing.'). Overall, it avoids unnecessary verbosity.

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 complexity of code validation, lack of annotations, and no output schema, the description is incomplete. It doesn't explain what the tool returns (e.g., validation results, errors, formatted code), behavioral details, or how it differs from similar tools like 'lint_code'. For a tool with no structured support, more descriptive context is needed.

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 description coverage is 100%, so the schema already documents both parameters ('code' and 'language') with clear descriptions. The description adds minimal value beyond the schema by implying the parameters are used for validation, but doesn't provide additional context like example values or constraints beyond what's in the schema.

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 tool's purpose with specific verbs ('validates code syntax and formatting') and resources ('code snippets'), and mentions the mechanism ('using available linters'). However, it doesn't explicitly differentiate from sibling tools like 'lint_code' or 'format_code', which may have overlapping functionality.

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

Usage Guidelines3/5

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

The description provides some context on when to use the tool ('before finalizing'), but it doesn't offer explicit guidance on when to use this tool versus alternatives like 'lint_code' or 'format_code'. The usage is implied rather than clearly distinguished from sibling tools.

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/millsydotdev/Code-MCP'

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