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: '' };
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions the tool's purpose (verification to prevent hallucinations) but lacks details on behavioral traits such as what happens on failure (e.g., returns errors, blocks suggestions), performance characteristics (e.g., speed, rate limits), or authentication needs. For a verification tool with zero annotation coverage, this is a significant gap.

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 extremely concise and front-loaded with a single sentence that directly states the critical action and purpose. There is no wasted text, and every word earns its place by emphasizing urgency ('CRITICAL') and specifying the context ('before suggesting any code').

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 the complexity (a verification tool with 3 required parameters), no annotations, and no output schema, the description is incomplete. It lacks details on behavioral traits, output format, or error handling, which are crucial for an agent to use it effectively. However, the purpose and usage guidelines are clear, providing a minimal viable basis for use.

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%, with clear descriptions for all three parameters (imports, methods, patterns). The description adds no additional parameter semantics beyond what the schema provides, such as examples of valid inputs or constraints. Since the schema does the heavy lifting, the baseline score of 3 is appropriate, as the description doesn't compensate but also doesn't detract.

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: to verify imports, methods, and patterns before suggesting code to prevent hallucinations. It specifies the verb 'check/verify' and the resource 'imports, methods, patterns', making it distinct from siblings like 'validate_generated_code' or 'detect_existing_patterns'. However, it doesn't explicitly differentiate from all siblings, such as 'check_security_compliance', which might also involve verification.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit usage guidelines: 'AI must use this before suggesting any code'. This clearly states when to use the tool (before code suggestions) and implies when not to use it (e.g., after code is generated or for other tasks). It doesn't name alternatives, but the context is sufficiently clear given the tool's preventive role.

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

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