Skip to main content
Glama
AlyssonM

HiveAuth MCP Server

by AlyssonM

batch_verify_credentials

Verify multiple W3C verifiable credentials simultaneously with parallel processing, error handling options, and detailed verification statistics.

Instructions

Verify multiple verifiable credentials efficiently. Supports parallel processing, early termination on errors, and detailed verification statistics.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
credentialsYes
parallelNoWhether to process credentials in parallel
stopOnFirstErrorNoWhether to stop verification on first error

Implementation Reference

  • The core handler function that executes the batch verification logic. It validates input using the schema, processes credentials in parallel or sequentially against the HiveAuth API, handles errors, generates detailed summaries and JSON output.
    export async function batchVerifyCredentials(args: any): Promise<CallToolResult> {
      // Validate and sanitize input
      const validation = validateAndSanitizeInput(BatchVerifyCredentialsInputSchema, args, 'batch_verify_credentials');
      
      if (!validation.success) {
        return createValidationErrorResult(validation.error!);
      }
    
      const data = validation.data!;
      const { credentials, parallel = true, stopOnFirstError = false } = data;
    
      const HIVEAUTH_API_BASE_URL = process.env.HIVEAUTH_API_BASE_URL || 'http://localhost:3000';
      const VERIFY_ENDPOINT = `${HIVEAUTH_API_BASE_URL}/api/verify`;
    
      const startTime = Date.now();
      const results: any[] = [];
      const errors: any[] = [];
      let stopped = false;
    
      try {
        console.log(`[BatchVerify] Starting batch verification of ${credentials.length} credentials`);
        console.log(`[BatchVerify] Config: parallel=${parallel}, stopOnFirstError=${stopOnFirstError}`);
    
        if (parallel && !stopOnFirstError) {
          // Process all credentials in parallel
          const promises = credentials.map(async (credential, index) => {
            try {
              const response = await fetch(VERIFY_ENDPOINT, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ credential }),
              });
    
              if (!response.ok) {
                const errorData = await response.json().catch(() => ({ message: response.statusText }));
                throw new Error(`API Error: ${errorData.message}`);
              }
    
              const result = await response.json();
              return { 
                index, 
                success: true, 
                verified: result.verified,
                credential,
                result,
                credentialId: credential.id || `credential-${index + 1}`
              };
            } catch (error: any) {
              return { 
                index, 
                success: false, 
                verified: false,
                error: error.message,
                credentialId: credential.id || `credential-${index + 1}`
              };
            }
          });
    
          const allResults = await Promise.all(promises);
          
          // Separate results
          allResults.forEach(result => {
            if (result.success) {
              results.push(result);
            } else {
              errors.push(result);
            }
          });
        } else {
          // Process sequentially or with early termination
          for (let index = 0; index < credentials.length; index++) {
            if (stopped) break;
            
            const credential = credentials[index];
            
            try {
              const response = await fetch(VERIFY_ENDPOINT, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ credential }),
              });
    
              if (!response.ok) {
                const errorData = await response.json().catch(() => ({ message: response.statusText }));
                throw new Error(`API Error: ${errorData.message}`);
              }
    
              const result = await response.json();
              
              const verificationResult = { 
                index, 
                success: true, 
                verified: result.verified,
                credential,
                result,
                credentialId: credential.id || `credential-${index + 1}`
              };
              
              results.push(verificationResult);
              
              // Stop on first verification failure if requested
              if (stopOnFirstError && !result.verified) {
                stopped = true;
                console.log(`[BatchVerify] Stopping on first verification failure at index ${index}`);
              }
            } catch (error: any) {
              const errorResult = { 
                index, 
                success: false, 
                verified: false,
                error: error.message,
                credentialId: credential.id || `credential-${index + 1}`
              };
              
              errors.push(errorResult);
              
              // Stop on first error if requested
              if (stopOnFirstError) {
                stopped = true;
                console.log(`[BatchVerify] Stopping on first error at index ${index}`);
              }
            }
          }
        }
    
        const endTime = Date.now();
        const duration = endTime - startTime;
        const totalProcessed = results.length + errors.length;
        const validCredentials = results.filter(r => r.verified).length;
        const invalidCredentials = results.filter(r => !r.verified).length;
        const apiErrors = errors.length;
    
        // Generate detailed summary
        const summary = [
          `🔍 **Batch Credential Verification Results**`,
          ``,
          `• Total Processed: ${totalProcessed}/${credentials.length}`,
          `• Valid Credentials: ${validCredentials} ✅`,
          `• Invalid Credentials: ${invalidCredentials} ❌`,
          `• API Errors: ${apiErrors} 🚫`,
          `• Processing Mode: ${parallel ? 'Parallel' : 'Sequential'}`,
          `• Duration: ${duration}ms`,
          `• Average per credential: ${Math.round(duration / totalProcessed)}ms`,
          ``
        ];
    
        if (stopped) {
          summary.push(`⚠️ **Early Termination**: Stopped processing due to stopOnFirstError setting`);
          summary.push(``);
        }
    
        // Valid credentials
        const validResults = results.filter(r => r.verified);
        if (validResults.length > 0) {
          summary.push(`**✅ Valid Credentials (${validResults.length}):**`);
          validResults.forEach(result => {
            const issuer = result.credential.issuer;
            const issuerInfo = typeof issuer === 'string' ? issuer : issuer?.id || 'Unknown';
            const types = result.credential.type?.filter((t: string) => t !== 'VerifiableCredential').join(', ') || 'Unknown';
            summary.push(`${result.index + 1}. **${result.credentialId}** - ${types} (Issuer: ${issuerInfo})`);
          });
          summary.push(``);
        }
    
        // Invalid credentials
        const invalidResults = results.filter(r => !r.verified);
        if (invalidResults.length > 0) {
          summary.push(`**❌ Invalid Credentials (${invalidResults.length}):**`);
          invalidResults.forEach(result => {
            const reason = result.result?.message || 'Verification failed';
            summary.push(`${result.index + 1}. **${result.credentialId}** - ${reason}`);
          });
          summary.push(``);
        }
    
        // API errors
        if (apiErrors > 0) {
          summary.push(`**🚫 API Errors (${apiErrors}):**`);
          errors.forEach(error => {
            summary.push(`${error.index + 1}. **${error.credentialId}** - ${error.error}`);
          });
          summary.push(``);
        }
    
        // Performance insights
        if (parallel && totalProcessed > 1) {
          const sequentialEstimate = duration * totalProcessed;
          const speedup = Math.round((sequentialEstimate / duration) * 10) / 10;
          summary.push(`**⚡ Performance:**`);
          summary.push(`• Parallel speedup: ~${speedup}x faster than sequential`);
          summary.push(`• Verification rate: ${Math.round(totalProcessed / (duration / 1000))} credentials/second`);
        }
    
        // Recommendations
        summary.push(`**💡 Recommendations:**`);
        if (invalidCredentials > 0) {
          summary.push(`• Review invalid credentials for common issues (expired, revoked, signature problems)`);
        }
        if (apiErrors > 0) {
          summary.push(`• Check network connectivity and HiveAuth API availability`);
        }
        if (validCredentials / totalProcessed < 0.8) {
          summary.push(`• Consider reviewing credential sources - low validation rate detected`);
        }
    
        return {
          content: [
            {
              type: 'text',
              text: summary.join('\n')
            },
            {
              type: 'text',
              text: `\`\`\`json\n${JSON.stringify({
                summary: {
                  totalProcessed,
                  totalCredentials: credentials.length,
                  validCredentials,
                  invalidCredentials,
                  apiErrors,
                  duration,
                  parallel,
                  stopOnFirstError,
                  stopped
                },
                validCredentials: validResults.map(r => ({
                  index: r.index,
                  credentialId: r.credentialId,
                  verified: true,
                  types: r.credential.type
                })),
                invalidCredentials: invalidResults.map(r => ({
                  index: r.index,
                  credentialId: r.credentialId,
                  verified: false,
                  reason: r.result?.message
                })),
                errors: errors.map(e => ({
                  index: e.index,
                  credentialId: e.credentialId,
                  error: e.error
                }))
              }, null, 2)}\n\`\`\``
            }
          ]
        };
      } catch (error: any) {
        return {
          content: [
            {
              type: 'text',
              text: `Failed to verify credentials in batch: ${error.message}`
            }
          ],
          isError: true
        };
      }
    }
  • Zod input schema defining the expected parameters for the batch_verify_credentials tool: array of credentials (up to 100), parallel processing flag, and stop-on-first-error flag.
    export const BatchVerifyCredentialsInputSchema = z.object({
      credentials: z.array(CredentialSchema).min(1).max(100, 'Maximum 100 credentials per batch'),
      parallel: z.boolean().default(true).describe('Whether to process credentials in parallel'),
      stopOnFirstError: z.boolean().default(false).describe('Whether to stop verification on first error')
    });
  • src/index.ts:104-105 (registration)
    Registration in the main MCP server switch statement that dispatches calls to the batchVerifyCredentials handler function.
    case 'batch_verify_credentials':
      return await batchVerifyCredentials(args);
  • src/index.ts:27-27 (registration)
    Import statement bringing the handler into the main server file for use in tool dispatching.
    import { batchVerifyCredentials } from './tools/batchVerifyCredentials.js';
  • TypeScript type definition inferred from the input schema for type safety.
    export type BatchVerifyCredentialsInput = z.infer<typeof BatchVerifyCredentialsInputSchema>;
Behavior4/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 effectively describes key behavioral traits: 'parallel processing' (performance characteristic), 'early termination on errors' (error handling), and 'detailed verification statistics' (output behavior). This goes beyond the input schema by explaining how the tool operates and what results to expect, though it doesn't cover aspects like rate limits or authentication needs.

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, well-structured sentence that efficiently communicates the tool's purpose and key features. Every phrase ('Verify multiple verifiable credentials efficiently,' 'Supports parallel processing,' 'early termination on errors,' 'detailed verification statistics') adds value without redundancy. It's front-loaded with the core purpose and follows with supporting details.

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?

For a tool with 3 parameters, no annotations, and no output schema, the description provides a good overview of behavior and purpose. However, it lacks details on output format (beyond 'statistics'), error handling specifics, or integration with sibling tools. Given the complexity of credential verification and the absence of structured metadata, the description is adequate but leaves gaps an agent might need to infer.

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 67% (2 out of 3 parameters have descriptions). The description doesn't add any parameter-specific information beyond what's in the schema. It mentions general features like 'parallel processing' and 'early termination on errors,' which align with the 'parallel' and 'stopOnFirstError' parameters but don't provide additional semantic context. Given the moderate schema coverage, the description doesn't compensate for gaps but doesn't detract either.

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: 'Verify multiple verifiable credentials efficiently.' It specifies the verb ('verify'), resource ('verifiable credentials'), and scope ('multiple'). However, it doesn't explicitly distinguish this batch operation from the sibling 'verify_credential' tool, which appears to handle single credentials.

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

Usage Guidelines3/5

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

The description implies usage context through 'efficiently' and mentions features like 'parallel processing' and 'early termination on errors,' which suggest when batch processing is advantageous. However, it doesn't provide explicit guidance on when to use this tool versus the 'verify_credential' sibling or other verification-related tools, nor does it mention prerequisites or 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/AlyssonM/hiveauth-mcp'

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