Skip to main content
Glama
bswa006

AI Agent Template MCP Server

by bswa006

check_before_suggesting

Verifies imports, methods, and patterns to ensure code suggestions are accurate and prevent hallucinations before implementation.

Instructions

CRITICAL: AI must use this before suggesting any code to prevent hallucinations

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
importsYesList of imports to verify (e.g., ["react", "useState from react"])
methodsYesList of methods to verify (e.g., ["Array.prototype.findLast", "String.prototype.replaceAll"])
patternsYesList of patterns to verify (e.g., ["async/await", "error boundaries"])

Implementation Reference

  • Core handler function that implements the 'check_before_suggesting' tool logic: validates imports against package.json dependencies, checks methods for compatibility issues, validates patterns for deprecated/risky code, and collects issues/warnings.
    export async function checkBeforeSuggesting(
      imports: string[],
      methods: string[],
      patterns?: string[]
    ): Promise<HallucinationCheckResult> {
      const result: HallucinationCheckResult = {
        safe: true,
        issues: [],
        warnings: [],
      };
    
      // Check imports
      const projectPath = process.env.PROJECT_PATH || process.cwd();
      const packageJsonPath = join(projectPath, 'package.json');
      
      if (existsSync(packageJsonPath)) {
        const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
        const allDeps = {
          ...packageJson.dependencies,
          ...packageJson.devDependencies,
          ...packageJson.peerDependencies,
        };
    
        for (const imp of imports) {
          // Extract package name from import
          const packageName = extractPackageName(imp);
          
          if (!isBuiltinModule(packageName) && !allDeps[packageName]) {
            result.safe = false;
            result.issues.push({
              type: 'import',
              item: imp,
              issue: `Package "${packageName}" not found in dependencies`,
              suggestion: `Check if the package is installed or use a different approach`,
            });
          }
        }
      }
    
      // Check methods
      for (const method of methods) {
        const validation = validateMethod(method);
        if (!validation.valid) {
          result.safe = false;
          result.issues.push({
            type: 'method',
            item: method,
            issue: validation.issue,
            suggestion: validation.suggestion,
          });
        }
      }
    
      // Check patterns
      if (patterns) {
        for (const pattern of patterns) {
          const validation = validatePattern(pattern);
          if (!validation.valid) {
            result.safe = false;
            result.issues.push({
              type: 'pattern',
              item: pattern,
              issue: validation.issue,
              suggestion: validation.suggestion,
            });
          }
        }
      }
    
      // Add warnings for common mistakes
      if (methods.some(m => m.includes('findLast'))) {
        result.warnings.push(
          'Array.prototype.findLast() is not available in all environments. Consider using a polyfill or alternative approach.'
        );
      }
    
      if (imports.some(i => i.includes('react') && i.includes('useSyncExternalStore'))) {
        result.warnings.push(
          'useSyncExternalStore is only available in React 18+. Verify the project React version.'
        );
      }
    
      return result;
    }
  • Input schema definition for the 'check_before_suggesting' tool, specifying parameters for imports, methods, and patterns.
      name: 'check_before_suggesting',
      description: 'CRITICAL: AI must use this before suggesting any code to prevent hallucinations',
      inputSchema: {
        type: 'object',
        properties: {
          imports: {
            type: 'array',
            items: { type: 'string' },
            description: 'List of imports to verify (e.g., ["react", "useState from react"])',
          },
          methods: {
            type: 'array',
            items: { type: 'string' },
            description: 'List of methods to verify (e.g., ["Array.prototype.findLast", "String.prototype.replaceAll"])',
          },
          patterns: {
            type: 'array',
            items: { type: 'string' },
            description: 'List of patterns to verify (e.g., ["async/await", "error boundaries"])',
          },
        },
        required: ['imports', 'methods', 'patterns'],
      },
    },
  • Tool registration and execution handler in the main tools dispatcher: parses input with Zod, calls the checkBeforeSuggesting handler, and returns JSON result.
    case 'check_before_suggesting': {
      const params = z.object({
        imports: z.array(z.string()),
        methods: z.array(z.string()),
        patterns: z.array(z.string()).optional(),
      }).parse(args);
      
      const result = await checkBeforeSuggesting(
        params.imports,
        params.methods,
        params.patterns
      );
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2),
          },
        ],
      };
    }
  • Registration of the tools/list endpoint that returns the tool definitions including 'check_before_suggesting'.
    server.setRequestHandler(ListToolsRequestSchema, async () => {
      console.error(`Handling tools/list request, returning ${toolDefinitions.length} tools`);
      return { tools: toolDefinitions };
    });
  • Helper function validateMethod that checks for known problematic methods and returns validation issues/suggestions.
    function validateMethod(method: string): MethodValidation {
      const knownIssues: Record<string, MethodValidation> = {
        'Array.prototype.findLast': {
          valid: false,
          issue: 'Not available in all JavaScript environments',
          suggestion: 'Use arr.slice().reverse().find() or a polyfill',
        },
        'Object.hasOwn': {
          valid: false,
          issue: 'ES2022 feature, not widely supported',
          suggestion: 'Use Object.prototype.hasOwnProperty.call(obj, prop)',
        },
        'String.prototype.replaceAll': {
          valid: false,
          issue: 'Not available in older environments',
          suggestion: 'Use str.replace(/pattern/g, replacement)',
        },
        'Promise.any': {
          valid: false,
          issue: 'ES2021 feature, check environment support',
          suggestion: 'Use Promise.race() or a polyfill',
        },
        'WeakRef': {
          valid: false,
          issue: 'ES2021 feature, limited support',
          suggestion: 'Consider if WeakRef is truly necessary',
        },
      };
    
      if (knownIssues[method]) {
        return knownIssues[method];
      }
    
      // Check for React hooks in wrong context
      if (method.includes('use') && method[3] === method[3].toUpperCase()) {
        if (method.includes('useSyncExternalStore') || method.includes('useTransition')) {
          return {
            valid: false,
            issue: 'React 18+ hook, may not be available',
            suggestion: 'Check React version or use alternative approach',
          };
        }
      }
    
      return { valid: true, issue: '' };
    }

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/bswa006/mcp-context-manager'

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