Skip to main content
Glama

create_rule

Create a new Semgrep rule to detect code patterns by specifying a search pattern, target language, and message. Output the rule to a file for use in static analysis.

Instructions

Creates a new Semgrep rule

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
output_pathYesAbsolute path for output rule file
patternYesSearch pattern for the rule
languageYesTarget language for the rule
messageYesMessage to display when rule matches
severityNoRule severity (ERROR, WARNING, INFO)WARNING
idNoRule identifiercustom_rule

Implementation Reference

  • The handleCreateRule method is the handler for the 'create_rule' tool. It validates required arguments (output_path, pattern, language, message), validates the path and rule fields, constructs a YAML rule string using escapeYamlScalar to prevent YAML injection, and writes the rule file to disk.
    private async handleCreateRule(args: any) {
      if (!args.output_path || !args.pattern || !args.language || !args.message) {
        throw new McpError(
          ErrorCode.InvalidParams,
          'output_path, pattern, language and message are required'
        );
      }
    
      const outputPath = validateAbsolutePath(args.output_path, 'output_path');
      const id = validateRuleField(args.id ?? 'custom_rule', 'id', ALLOWED_RULE_ID);
      const language = validateRuleField(args.language, 'language', ALLOWED_LANGUAGE);
      const severity = validateRuleSeverity(args.severity ?? 'WARNING');
    
      // escapeYamlScalar uses JSON.stringify to escape user values, preventing YAML injection
      const ruleYaml = [
        'rules:',
        `  - id: ${id}`,
        `    pattern: ${escapeYamlScalar(args.pattern)}`,
        `    message: ${escapeYamlScalar(args.message)}`,
        `    languages: [${language}]`,
        `    severity: ${severity}`,
        ''
      ].join('\n');
    
      try {
        await writeFile(outputPath, ruleYaml, 'utf-8');
        return {
          content: [{ type: 'text', text: `Rule successfully created at ${outputPath}` }]
        };
      } catch (error: any) {
        return {
          content: [{ type: 'text', text: `Error creating rule: ${error.message}` }],
          isError: true
        };
      }
    }
  • src/index.ts:299-322 (registration)
    The tool 'create_rule' is registered in the ListToolsRequestSchema handler with its name, description, and inputSchema defining required (output_path, pattern, language, message) and optional (severity, id) parameters.
    {
      name: 'create_rule',
      description: 'Creates a new Semgrep rule',
      inputSchema: {
        type: 'object',
        properties: {
          output_path: { type: 'string', description: 'Absolute path for output rule file' },
          pattern: { type: 'string', description: 'Search pattern for the rule' },
          language: { type: 'string', description: 'Target language for the rule' },
          message: { type: 'string', description: 'Message to display when rule matches' },
          severity: {
            type: 'string',
            description: 'Rule severity (ERROR, WARNING, INFO)',
            default: 'WARNING'
          },
          id: {
            type: 'string',
            description: 'Rule identifier',
            default: 'custom_rule'
          }
        },
        required: ['output_path', 'pattern', 'language', 'message']
      }
    },
  • src/index.ts:381-383 (registration)
    The tool dispatch in CallToolRequestSchema routes 'create_rule' to the handleCreateRule method.
    case 'create_rule':
      return await this.handleCreateRule(request.params.arguments);
    case 'filter_results':
  • escapeYamlScalar helper function used by handleCreateRule to safely escape YAML string values using JSON.stringify, preventing YAML injection attacks.
    function escapeYamlScalar(value: string): string {
      if (typeof value !== 'string') {
        throw new McpError(ErrorCode.InvalidParams, 'YAML scalar value must be a string');
      }
      return JSON.stringify(value);
    }
  • validateRuleField helper function used by handleCreateRule to validate the rule id and language fields against regex patterns (ALLOWED_RULE_ID and ALLOWED_LANGUAGE).
    export function validateRuleField(
      value: string,
      paramName: string,
      pattern: RegExp
    ): string {
      if (typeof value !== 'string' || !pattern.test(value)) {
        throw new McpError(
          ErrorCode.InvalidParams,
          `${paramName} contains invalid characters or exceeds allowed format`
        );
      }
      return value;
    }
Behavior1/5

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

With no annotations, the description must disclose behavioral traits. It only states 'Creates a new Semgrep rule' with no information about side effects (e.g., overwriting existing files), permissions, or error handling.

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

Conciseness3/5

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

The description is a single sentence, which is concise but lacks structure. It front-loads the action but provides no additional detail, making it barely adequate.

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 creates a file (output_path required) and has no output schema, the description should explain return behavior (e.g., success indication) or file naming. It does not, leaving significant gaps 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?

Input schema has 100% coverage with clear parameter descriptions. The tool description adds no additional meaning beyond the schema, meeting the baseline for high coverage.

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 uses a specific verb 'Creates' and resource 'a new Semgrep rule', making the core action clear. It naturally distinguishes from siblings which focus on analysis, comparison, and listing, not creation.

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 versus alternatives. The description does not indicate prerequisites (e.g., rule syntax knowledge) or situations where other tools might be more appropriate.

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/VetCoders/mcp-server-semgrep'

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