Skip to main content
Glama
renjismzy

Smart Code Reviewer

by renjismzy

detect_security_issues

Identify security vulnerabilities and risks in code to improve software safety and prevent potential exploits.

Instructions

检测代码中的安全漏洞和风险

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYes要检测的代码
languageYes编程语言

Implementation Reference

  • Core handler function that performs security scanning by detecting common and language-specific issues using regex patterns, aggregates results, and computes risk score.
    export async function detectSecurityIssues(
      code: string,
      language: string
    ): Promise<SecurityScanResult> {
      const issues: SecurityIssue[] = [];
      
      // 通用安全检测
      await detectCommonSecurityIssues(code, language, issues);
      
      // 语言特定安全检测
      switch (language.toLowerCase()) {
        case 'javascript':
        case 'typescript':
          await detectJavaScriptSecurityIssues(code, issues);
          break;
        case 'python':
          await detectPythonSecurityIssues(code, issues);
          break;
        case 'java':
          await detectJavaSecurityIssues(code, issues);
          break;
        case 'sql':
          await detectSQLSecurityIssues(code, issues);
          break;
      }
      
      return {
        language,
        totalIssues: issues.length,
        criticalIssues: issues.filter(i => i.severity === 'critical').length,
        highIssues: issues.filter(i => i.severity === 'high').length,
        mediumIssues: issues.filter(i => i.severity === 'medium').length,
        lowIssues: issues.filter(i => i.severity === 'low').length,
        issues,
        recommendations: generateSecurityRecommendations(issues),
        riskScore: calculateRiskScore(issues)
      };
    }
  • MCP server handler for the tool: validates input parameters using Zod, calls the core detectSecurityIssues function, and formats the response as MCP content.
    private async handleDetectSecurityIssues(args: any) {
      const schema = z.object({
        code: z.string(),
        language: z.string()
      });
    
      const { code, language } = schema.parse(args);
      const result = await detectSecurityIssues(code, language);
    
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2)
          }
        ]
      };
    }
  • src/index.ts:89-106 (registration)
    Tool registration in the ListTools response, defining name, description, and input schema.
    {
      name: 'detect_security_issues',
      description: '检测代码中的安全漏洞和风险',
      inputSchema: {
        type: 'object',
        properties: {
          code: {
            type: 'string',
            description: '要检测的代码'
          },
          language: {
            type: 'string',
            description: '编程语言'
          }
        },
        required: ['code', 'language']
      }
    },
  • TypeScript interfaces defining the output structure: SecurityScanResult for the scan result and SecurityIssue for individual issues.
    export interface SecurityScanResult {
      language: string;
      totalIssues: number;
      criticalIssues: number;
      highIssues: number;
      mediumIssues: number;
      lowIssues: number;
      issues: SecurityIssue[];
      recommendations: string[];
      riskScore: number;
    }
    
    export interface SecurityIssue {
      type: 'hardcoded-credentials' | 'code-injection' | 'sql-injection' | 'xss' | 
            'unsafe-deserialization' | 'weak-randomness' | 'information-disclosure' |
            'regex-dos' | 'prototype-pollution' | 'xxe' | 'insecure-temp-file' |
            'dangerous-operation';
      severity: 'critical' | 'high' | 'medium' | 'low';
      message: string;
      description: string;
      line: number;
      column: number;
      cwe: string;
      recommendation: string;
    }
  • Helper function for detecting common security issues like hardcoded credentials, code injection, weak randomness, and debug leaks using regex patterns.
    async function detectCommonSecurityIssues(
      code: string,
      language: string,
      issues: SecurityIssue[]
    ): Promise<void> {
      const lines = code.split('\n');
      
      lines.forEach((line, index) => {
        const lineNumber = index + 1;
        const trimmedLine = line.trim().toLowerCase();
        
        // 检测硬编码密码
        const passwordPatterns = [
          /password\s*[=:]\s*["'][^"']+["']/i,
          /pwd\s*[=:]\s*["'][^"']+["']/i,
          /secret\s*[=:]\s*["'][^"']+["']/i,
          /api[_-]?key\s*[=:]\s*["'][^"']+["']/i,
          /token\s*[=:]\s*["'][^"']+["']/i
        ];
        
        passwordPatterns.forEach(pattern => {
          if (pattern.test(line)) {
            issues.push({
              type: 'hardcoded-credentials',
              severity: 'critical',
              message: '检测到硬编码的敏感信息(密码、密钥等)',
              description: '硬编码的敏感信息可能被恶意用户获取,应使用环境变量或配置文件',
              line: lineNumber,
              column: line.search(pattern) + 1,
              cwe: 'CWE-798',
              recommendation: '使用环境变量或安全的配置管理系统存储敏感信息'
            });
          }
        });
        
        // 检测潜在的代码注入
        const injectionPatterns = [
          /eval\s*\(/i,
          /exec\s*\(/i,
          /system\s*\(/i,
          /shell_exec\s*\(/i,
          /passthru\s*\(/i
        ];
        
        injectionPatterns.forEach(pattern => {
          if (pattern.test(line)) {
            issues.push({
              type: 'code-injection',
              severity: 'critical',
              message: '检测到潜在的代码注入风险',
              description: '使用动态代码执行函数可能导致代码注入攻击',
              line: lineNumber,
              column: line.search(pattern) + 1,
              cwe: 'CWE-94',
              recommendation: '避免使用动态代码执行,使用更安全的替代方案'
            });
          }
        });
        
        // 检测不安全的随机数生成
        const weakRandomPatterns = [
          /math\.random\s*\(/i,
          /random\.random\s*\(/i,
          /rand\s*\(/i
        ];
        
        weakRandomPatterns.forEach(pattern => {
          if (pattern.test(line)) {
            issues.push({
              type: 'weak-randomness',
              severity: 'medium',
              message: '使用了不安全的随机数生成器',
              description: '弱随机数生成器可能被预测,不适用于安全相关场景',
              line: lineNumber,
              column: line.search(pattern) + 1,
              cwe: 'CWE-338',
              recommendation: '使用密码学安全的随机数生成器'
            });
          }
        });
        
        // 检测调试信息泄露
        const debugPatterns = [
          /console\.log\s*\(.*(password|token|key|secret)/i,
          /print\s*\(.*(password|token|key|secret)/i,
          /system\.out\.println\s*\(.*(password|token|key|secret)/i
        ];
        
        debugPatterns.forEach(pattern => {
          if (pattern.test(line)) {
            issues.push({
              type: 'information-disclosure',
              severity: 'high',
              message: '检测到敏感信息可能通过调试输出泄露',
              description: '在日志或控制台输出中包含敏感信息可能导致信息泄露',
              line: lineNumber,
              column: line.search(pattern) + 1,
              cwe: 'CWE-532',
              recommendation: '移除或过滤敏感信息的调试输出'
            });
          }
        });
      });
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states what the tool does (detects security issues) but doesn't describe how it behaves: whether it's read-only or destructive, what permissions are needed, how results are returned, or any rate limits. For a security analysis tool with zero annotation coverage, this leaves significant gaps in understanding operational characteristics.

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, efficient sentence in Chinese that directly states the tool's purpose with zero wasted words. It's appropriately sized and front-loaded with the essential information.

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 this is a security analysis tool with no annotations and no output schema, the description is incomplete. It doesn't explain what types of vulnerabilities are detected, how results are formatted, whether it's a lightweight scan or deep analysis, or any limitations. For a tool that presumably returns important security findings, more context about output and behavior 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 descriptions. The tool description doesn't add any parameter-specific information beyond what's in the schema. According to scoring rules, when schema coverage is high (>80%), the baseline is 3 even with no param info in the description.

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 as detecting security vulnerabilities and risks in code, using specific verbs ('检测') and resources ('代码中的安全漏洞和风险'). It distinguishes from siblings like analyze_code_quality (general quality) and calculate_complexity (complexity metrics), but doesn't explicitly mention this differentiation in the description text itself.

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?

The description provides no guidance on when to use this tool versus alternatives like analyze_code_quality or suggest_refactoring. It doesn't specify prerequisites, context, or exclusions. The agent must infer usage from the purpose alone without explicit direction.

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/renjismzy/mcp-code'

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