Skip to main content
Glama
isagasi

CodeGuard MCP Server

by isagasi

validate_code_security

Validate a code snippet in any programming language against security rules and receive applicable security instructions.

Instructions

Validate code snippet against security rules and return applicable instructions

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesCode snippet to validate
languageYesProgramming language of the code

Implementation Reference

  • The main handler function `validateCodeSecurity` that executes the 'validate_code_security' tool. It takes code and language args, matches applicable security instructions, formats them with a header and rule listing, and returns the result.
    function validateCodeSecurity(
      args: Record<string, unknown>,
      instructions: Instruction[]
    ) {
      const code = args.code as string;
      const language = args.language as string;
      
      if (!code || !language) {
        return {
          content: [
            {
              type: 'text',
              text: 'Error: Both code and language are required',
            },
          ],
          isError: true,
        };
      }
      
      // Get applicable instructions
      const result = matchInstructions({ language }, instructions);
      
      // Build response with instructions and validation context
      const response = [
        `# Security Validation for ${language.toUpperCase()} Code`,
        '',
        `Analyzing the provided code against ${result.instructions.length} security rules...`,
        '',
        '## Applicable Security Rules:',
        '',
      ];
      
      result.instructions.forEach(i => {
        response.push(`### ${i.frontmatter.description}`);
        response.push('');
        response.push(i.content);
        response.push('');
        response.push('---');
        response.push('');
      });
      
      response.push('## Recommendation:');
      response.push('Review your code against the above security rules and ensure compliance.');
      
      return {
        content: [
          {
            type: 'text',
            text: response.join('\n'),
          },
        ],
        isError: false,
      };
    }
  • Input schema definition for the 'validate_code_security' tool, declaring 'code' (string) and 'language' (string) as required parameters.
    {
      name: 'validate_code_security',
      description: 'Validate code snippet against security rules and return applicable instructions',
      inputSchema: {
        type: 'object',
        properties: {
          code: {
            type: 'string',
            description: 'Code snippet to validate',
          },
          language: {
            type: 'string',
            description: 'Programming language of the code',
          },
        },
        required: ['code', 'language'],
      },
  • Registration/dispatch in `callTool` function: when name is 'validate_code_security', it calls the `validateCodeSecurity` function, connecting the MCP tool call to the handler.
    export function callTool(
      name: string,
      args: Record<string, unknown>,
      instructions: Instruction[]
    ) {
      if (name === 'get_security_instructions') {
        return getSecurityInstructions(args, instructions);
      }
      
      if (name === 'validate_code_security') {
        return validateCodeSecurity(args, instructions);
      }
  • src/index.ts:111-115 (registration)
    MCP server registration: the `CallToolRequestSchema` handler dispatches incoming tool calls to `callTool`, which routes to the validate_code_security handler.
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
      const { name, arguments: args = {} } = request.params;
      logToFile(`[MCP] CallTool: ${name} with args: ${JSON.stringify(args)}`);
      return callTool(name, args, instructions);
    });
  • The `matchInstructions` helper function used by validateCodeSecurity to score and match security rules against the provided language/context.
    export function matchInstructions(
      context: MatchContext,
      allInstructions: Instruction[]
    ): MatchResult {
      const scoredInstructions: ScoredInstruction[] = [];
      const matchedBy: MatchResult['metadata']['matchedBy'] = {};
      
      // Score all instructions
      for (const instruction of allInstructions) {
        const scored = scoreInstruction(instruction, context);
        if (scored.score > 0) {
          scoredInstructions.push(scored);
        }
      }
      
      // Sort by priority (high to low), then by score
      scoredInstructions.sort((a, b) => {
        if (a.priority !== b.priority) {
          return b.priority - a.priority;
        }
        return b.score - a.score;
      });
      
      // Count matches by type
      matchedBy.critical = scoredInstructions.filter(s => s.priority === Priority.CRITICAL).length;
      matchedBy.language = scoredInstructions.filter(s => s.matchReasons.includes('language')).length;
      matchedBy.filepath = scoredInstructions.filter(s => s.matchReasons.includes('filepath')).length;
      matchedBy.context = scoredInstructions.filter(s => s.matchReasons.includes('context')).length;
      
      // Priority breakdown
      const priorityBreakdown = {
        critical: scoredInstructions.filter(s => s.priority === Priority.CRITICAL).length,
        high: scoredInstructions.filter(s => s.priority === Priority.HIGH).length,
        medium: scoredInstructions.filter(s => s.priority === Priority.MEDIUM).length,
        low: scoredInstructions.filter(s => s.priority === Priority.LOW).length,
      };
      
      // Limit to top 15 rules to keep response size manageable
      const topInstructions = scoredInstructions.slice(0, 15);
      
      return {
        instructions: topInstructions.map(s => s.instruction),
        metadata: {
          totalMatched: scoredInstructions.length,
          matchedBy,
          priorityBreakdown,
        },
      };
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observedv1.0.10

TDQS

B3.2/5.0
Behavior2/5

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

No annotations are present, so the description carries the full burden of behavioral disclosure. It only states that validation returns instructions, but does not disclose potential side effects, authentication requirements, or the nature of the validation. For a security-related tool, this is insufficiently transparent.

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 sentence that is front-loaded with the core action ('Validate code snippet against security rules') and contains no redundant words. It is extremely concise and well-structured for easy scanning.

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?

The tool has no output schema and no annotations, yet the description only minimally addresses the return value ('return applicable instructions'). It does not explain what these instructions are, how validation works, or provide any safety/caveat context, leaving the tool under-specified for an agent.

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 input schema provides complete descriptions for both parameters (code and language), giving 100% schema coverage. The description adds no additional parameter meaning beyond what the schema already provides, so a baseline of 3 is appropriate.

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 validates a code snippet against security rules and returns applicable instructions. It distinguishes from the sibling tool get_security_instructions by emphasizing validation of a provided snippet rather than simply retrieving instructions, though the return of instructions creates some overlap.

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 implies when to use the tool (when a code snippet needs validation) but does not explicitly contrast with get_security_instructions or state when not to use it. No exclusions or alternative recommendations are provided, leaving the guidance implicit.

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

Deploy Server

Other Tools