Skip to main content
Glama
isagasi

CodeGuard MCP Server

by isagasi

get_security_instructions

Retrieve security rules for code generation based on programming language, context keywords, or file paths to ensure adherence to security best practices.

Instructions

Get security instructions for code generation. Returns applicable security rules based on language, context, or file path.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
languageNoProgramming language (python, javascript, typescript, java, c, etc.)
contextNoContext keywords (auth, crypto, database, api, password, hash, etc.)
filepathNoFile path for pattern matching (e.g., src/auth/login.ts)

Implementation Reference

  • The main handler function for get_security_instructions tool. It accepts args (language, context, filepath), calls matchInstructions to find applicable security rules, formats results as markdown, and returns them in MCP tool response format with content array.
    function getSecurityInstructions(
      args: Record<string, unknown>,
      instructions: Instruction[]
    ) {
      const language = args.language as string | undefined;
      const context = args.context as string | undefined;
      const filepath = args.filepath as string | undefined;
      
      // Match instructions
      const result = matchInstructions(
        { language, context, filepath },
        instructions
      );
      
      // Format as markdown
      const content = result.instructions
        .map(i => {
          return `## ${i.frontmatter.description}\n\n${i.content}`;
        })
        .join('\n\n---\n\n');
      
      return {
        content: [
          {
            type: 'text',
            text: content || 'No specific security instructions matched. Follow general security best practices.',
          },
        ],
        isError: false,
      };
    }
  • Tool registration in listTools function. Defines the get_security_instructions tool with its name, description, and inputSchema (language, context, filepath properties). Also includes the callTool routing function that dispatches to the handler.
    export function listTools() {
      return {
        tools: [
          {
            name: 'get_security_instructions',
            description: 'Get security instructions for code generation. Returns applicable security rules based on language, context, or file path.',
            inputSchema: {
              type: 'object',
              properties: {
                language: {
                  type: 'string',
                  description: 'Programming language (python, javascript, typescript, java, c, etc.)',
                },
                context: {
                  type: 'string',
                  description: 'Context keywords (auth, crypto, database, api, password, hash, etc.)',
                },
                filepath: {
                  type: 'string',
                  description: 'File path for pattern matching (e.g., src/auth/login.ts)',
                },
              },
            },
          },
          {
            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'],
            },
          },
        ],
      };
    }
  • Core matchInstructions helper function that implements the matching logic. Scores instructions based on filepath patterns, language extensions, and context keywords, then sorts by priority and returns the top 15 matched instructions with metadata.
    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,
        },
      };
    }
  • Alternative handler for the same functionality in the prompts API. Returns the security instructions formatted as a prompt message with description and user role content, used for MCP prompt-based interactions.
    function getSecurityInstructions(args: Record<string, string>, instructions: Instruction[]) {
      const { language, context, filepath } = args;
      
      // Match instructions
      const result = matchInstructions(
        { language, context, filepath },
        instructions
      );
      
      // Format matched instructions
      const content = result.instructions
        .map(i => `# ${i.frontmatter.description}\n\n${i.content}`)
        .join('\n\n---\n\n');
      
      // Build context description
      const parts = [];
      if (language) parts.push(`language: ${language}`);
      if (context) parts.push(`context: ${context}`);
      if (filepath) parts.push(`file: ${filepath}`);
      const contextDesc = parts.length > 0 ? ` (${parts.join(', ')})` : '';
      
      return {
        description: `Security instructions for code generation${contextDesc}`,
        messages: [
          {
            role: 'user',
            content: {
              type: 'text',
              text: content || 'No specific instructions matched. Follow general security best practices.',
            },
          },
        ],
      };
    }
Behavior2/5

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

With no annotations provided, the description carries full burden but only states it 'Returns applicable security rules,' without detailing format, pagination, error handling, or rate limits. It mentions the basis for rules (language, context, file path) but lacks behavioral specifics like response structure or performance characteristics.

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 purpose and return basis. It is front-loaded with the main action, though could be slightly more structured by explicitly separating purpose from usage hints.

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

Completeness3/5

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

Given 3 parameters with full schema coverage and no output schema, the description adequately covers purpose but lacks details on return values, error cases, or integration with sibling tools. For a retrieval tool, it's minimally viable but misses opportunities to enhance context.

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 fully documents parameters. The description adds minimal value by listing the basis for rules (language, context, file path), aligning with schema but not providing additional syntax or constraints. Baseline 3 is appropriate as schema handles heavy lifting.

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: 'Get security instructions for code generation' specifies the action (get) and resource (security instructions). It distinguishes from the sibling 'validate_code_security' by focusing on retrieval rather than validation, though the distinction could be more explicit.

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 usage through 'based on language, context, or file path,' suggesting when to use it, but lacks explicit guidance on when to choose this over 'validate_code_security' or other alternatives. No exclusions or prerequisites are mentioned.

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/isagasi/codeguard-mcp-server'

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