Skip to main content
Glama
Meerkats-Ai

NeverBounce MCP Server

by Meerkats-Ai
index.ts8.56 kB
#!/usr/bin/env node import { Server } from '@modelcontextprotocol/sdk/server/index.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import { Tool, CallToolRequestSchema, ListToolsRequestSchema, ErrorCode, McpError, } from '@modelcontextprotocol/sdk/types.js'; import axios, { AxiosInstance } from 'axios'; import dotenv from 'dotenv'; dotenv.config(); // Tool definitions const VALIDATE_EMAIL_TOOL: Tool = { name: 'neverbounce_validate_email', description: 'Validate an email address to check if it\'s valid and deliverable.', inputSchema: { type: 'object', properties: { email: { type: 'string', description: 'The email address to validate', }, timeout: { type: 'number', description: 'Timeout in milliseconds (optional, default: 30000)', } }, required: ['email'], }, }; // Type definitions interface ValidateEmailParams { email: string; timeout?: number; } // Type guards function isValidateEmailParams(args: unknown): args is ValidateEmailParams { if ( typeof args !== 'object' || args === null || !('email' in args) || typeof (args as { email: unknown }).email !== 'string' ) { return false; } // Optional parameters if ( 'timeout' in args && (args as { timeout: unknown }).timeout !== undefined && typeof (args as { timeout: unknown }).timeout !== 'number' ) { return false; } return true; } // Server implementation const server = new Server( { name: 'neverbounce-mcp', version: '1.0.0', }, { capabilities: { tools: {}, logging: {}, }, } ); // Get API key from environment variables const NEVERBOUNCE_API_KEY = process.env.NEVERBOUNCE_API_KEY; const NEVERBOUNCE_API_URL = 'https://api.neverbounce.com/v4.2'; // Check if API key is provided if (!NEVERBOUNCE_API_KEY) { console.error('Error: NEVERBOUNCE_API_KEY environment variable is required'); process.exit(1); } // Configuration for retries and monitoring const CONFIG = { retry: { maxAttempts: Number(process.env.NEVERBOUNCE_RETRY_MAX_ATTEMPTS) || 3, initialDelay: Number(process.env.NEVERBOUNCE_RETRY_INITIAL_DELAY) || 1000, maxDelay: Number(process.env.NEVERBOUNCE_RETRY_MAX_DELAY) || 10000, backoffFactor: Number(process.env.NEVERBOUNCE_RETRY_BACKOFF_FACTOR) || 2, }, }; // Initialize Axios instance for API requests const apiClient: AxiosInstance = axios.create({ baseURL: NEVERBOUNCE_API_URL, headers: { 'Content-Type': 'application/json' } }); let isStdioTransport = false; function safeLog( level: | 'error' | 'debug' | 'info' | 'notice' | 'warning' | 'critical' | 'alert' | 'emergency', data: any ): void { if (isStdioTransport) { // For stdio transport, log to stderr to avoid protocol interference console.error( `[${level}] ${typeof data === 'object' ? JSON.stringify(data) : data}` ); } else { // For other transport types, use the normal logging mechanism server.sendLoggingMessage({ level, data }); } } // Add utility function for delay function delay(ms: number): Promise<void> { return new Promise((resolve) => setTimeout(resolve, ms)); } // Add retry logic with exponential backoff async function withRetry<T>( operation: () => Promise<T>, context: string, attempt = 1 ): Promise<T> { try { return await operation(); } catch (error) { const isRateLimit = error instanceof Error && (error.message.includes('rate limit') || error.message.includes('429')); if (isRateLimit && attempt < CONFIG.retry.maxAttempts) { const delayMs = Math.min( CONFIG.retry.initialDelay * Math.pow(CONFIG.retry.backoffFactor, attempt - 1), CONFIG.retry.maxDelay ); safeLog( 'warning', `Rate limit hit for ${context}. Attempt ${attempt}/${CONFIG.retry.maxAttempts}. Retrying in ${delayMs}ms` ); await delay(delayMs); return withRetry(operation, context, attempt + 1); } throw error; } } // Function to interpret NeverBounce verification results function interpretVerificationResult(result: number): string { switch (result) { case 0: return 'Valid'; case 1: return 'Invalid'; case 2: return 'Disposable'; case 3: return 'Catchall'; case 4: return 'Unknown'; default: return 'Unknown'; } } // Tool handlers server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [ VALIDATE_EMAIL_TOOL, ], })); server.setRequestHandler(CallToolRequestSchema, async (request) => { const startTime = Date.now(); try { const { name, arguments: args } = request.params; // Log incoming request with timestamp safeLog( 'info', `[${new Date().toISOString()}] Received request for tool: ${name}` ); if (!args) { throw new Error('No arguments provided'); } switch (name) { case 'neverbounce_validate_email': { if (!isValidateEmailParams(args)) { throw new McpError( ErrorCode.InvalidParams, 'Invalid arguments for neverbounce_validate_email. You must provide an email address.' ); } try { // URL encode the email address const encodedEmail = encodeURIComponent(args.email); const response = await withRetry( async () => apiClient.get(`/single/check?key=${NEVERBOUNCE_API_KEY}&email=${encodedEmail}&timeout=${args.timeout || 30000}`), 'validate email' ); const data = response.data; // Format the response for better readability const formattedResponse = { email: args.email, status: data.status, result: interpretVerificationResult(data.result), result_code: data.result, flags: data.flags || [], suggested_correction: data.suggested_correction || null, execution_time: data.execution_time }; return { content: [ { type: 'text', text: JSON.stringify(formattedResponse, null, 2), }, ], isError: false, }; } catch (error) { const errorMessage = axios.isAxiosError(error) ? `API Error: ${error.response?.data?.message || error.message}` : `Error: ${error instanceof Error ? error.message : String(error)}`; return { content: [{ type: 'text', text: errorMessage }], isError: true, }; } } default: return { content: [ { type: 'text', text: `Unknown tool: ${name}` }, ], isError: true, }; } } catch (error) { // Log detailed error information safeLog('error', { message: `Request failed: ${ error instanceof Error ? error.message : String(error) }`, tool: request.params.name, arguments: request.params.arguments, timestamp: new Date().toISOString(), duration: Date.now() - startTime, }); return { content: [ { type: 'text', text: `Error: ${error instanceof Error ? error.message : String(error)}`, }, ], isError: true, }; } finally { // Log request completion with performance metrics safeLog('info', `Request completed in ${Date.now() - startTime}ms`); } }); // Server startup async function runServer() { try { console.error('Initializing NeverBounce MCP Server...'); const transport = new StdioServerTransport(); // Detect if we're using stdio transport isStdioTransport = transport instanceof StdioServerTransport; if (isStdioTransport) { console.error( 'Running in stdio mode, logging will be directed to stderr' ); } await server.connect(transport); // Now that we're connected, we can send logging messages safeLog('info', 'NeverBounce MCP Server initialized successfully'); safeLog( 'info', `Configuration: API URL: ${NEVERBOUNCE_API_URL}` ); console.error('NeverBounce MCP Server running on stdio'); } catch (error) { console.error('Fatal error running server:', error); process.exit(1); } } runServer().catch((error: any) => { console.error('Fatal error running server:', error); process.exit(1); });

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/Meerkats-Ai/neverbounce-mcp-server'

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