Skip to main content
Glama

scan_directory

Scan a directory for security vulnerabilities and code quality issues using Semgrep static analysis. Specify the absolute directory path and optionally choose a rule configuration.

Instructions

Performs a Semgrep scan on a directory

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesAbsolute path to the directory to scan (must be within an allowed workspace root)
configNoSemgrep configuration (e.g. "auto" or absolute path to rule file)auto

Implementation Reference

  • Input schema definition for scan_directory tool, registered in ListToolsRequestSchema handler
    {
      name: 'scan_directory',
      description: 'Performs a Semgrep scan on a directory',
      inputSchema: {
        type: 'object',
        properties: {
          path: {
            type: 'string',
            description: 'Absolute path to the directory to scan (must be within an allowed workspace root)'
          },
          config: {
            type: 'string',
            description: 'Semgrep configuration (e.g. "auto" or absolute path to rule file)',
            default: 'auto'
          }
        },
        required: ['path']
      }
  • src/index.ts:375-376 (registration)
    Switch-case dispatch that routes scan_directory requests to handleScanDirectory
    case 'scan_directory':
      return await this.handleScanDirectory(request.params.arguments);
  • Core handler that validates path/config, builds semgrep args with --json output, executes semgrep scan via execFileAsync, and returns results or error
    private async handleScanDirectory(args: any) {
      if (!args.path) {
        throw new McpError(ErrorCode.InvalidParams, 'Path is required');
      }
    
      const scanPath = validateAbsolutePath(args.path, 'path');
      const config = args.config || 'auto';
      const configParam = validateAbsolutePath(config, 'config');
    
      try {
        // Use execFile with arg array to prevent shell injection (CWE-78 fix)
        const semgrepArgs = ['scan', '--json', '--config', configParam, scanPath];
    
        if (process.env.SEMGREP_APP_TOKEN && config.startsWith('r/')) {
          semgrepArgs.splice(1, 0, '--oauth-token', process.env.SEMGREP_APP_TOKEN);
        }
    
        const loggedArgs = semgrepArgs.map((arg, idx) =>
          idx > 0 && semgrepArgs[idx - 1] === '--oauth-token' ? '[REDACTED]' : arg
        );
        console.error(`Executing: semgrep ${loggedArgs.join(' ')}`);
    
        const { stdout } = await execFileAsync('semgrep', semgrepArgs, {
          maxBuffer: SEMGREP_MAX_BUFFER,
        });
    
        return {
          content: [{ type: 'text', text: stdout }]
        };
      } catch (error: any) {
        return {
          content: [{ type: 'text', text: `Error scanning: ${error.message}` }],
          isError: true
        };
      }
    }
  • Validates that the path/config is absolute, within allowed roots, and free of shell metacharacters; handles registry config refs (p/, r/, auto) for the config parameter
    export function validateAbsolutePath(pathToValidate: string, paramName: string): string {
      if (paramName === 'config' && (
        pathToValidate.startsWith('p/') ||
        pathToValidate.startsWith('r/') ||
        pathToValidate === 'auto'
      )) {
        return validateRegistryConfig(pathToValidate);
      }
    
      validateNoShellMetacharacters(pathToValidate, paramName);
    
      if (!path.isAbsolute(pathToValidate)) {
        throw new McpError(
          ErrorCode.InvalidParams,
          `${paramName} must be an absolute path. Received: ${pathToValidate}`
        );
      }
    
      const normalizedPath = resolvePathForValidation(pathToValidate);
    
      if (!path.isAbsolute(normalizedPath)) {
        throw new McpError(
          ErrorCode.InvalidParams,
          `${paramName} contains invalid path traversal sequences`
        );
      }
    
      const allowedRoots = getAllowedRoots();
      const isWithinAllowedRoots = allowedRoots.some((allowedRoot) =>
        isPathWithinRoot(allowedRoot, normalizedPath)
      );
    
      if (!isWithinAllowedRoots) {
        throw new McpError(
          ErrorCode.InvalidParams,
          `${paramName} must be within an allowed workspace root (${formatAllowedRoots(allowedRoots)})`
        );
      }
    
      return normalizedPath;
    }
Behavior2/5

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

No annotations provided; description only states the action without disclosing side effects, permissions, or output behavior.

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?

Single sentence is concise but lacks structure or front-loading of key details. Could be expanded to include usage context.

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; description does not explain return values, side effects, or prerequisites, making it incomplete for a scan tool.

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%; both 'path' and 'config' are described in the schema. Description adds no extra meaning beyond the schema.

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?

Clear verb+resource: 'Performs a Semgrep scan on a directory' distinguishes from siblings like analyze_results or list_rules.

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 (e.g., analyze_results) or any exclusions.

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