mail-mcp-server

Pink-Marlin-Digital/mail-mcp-server

3.2

If you are the rightful owner of mail-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.

A Model Context Protocol (MCP) server that provides email sending capabilities via HTTP API with JWT authentication and Gmail SMTP integration.

Tools
1
Resources
0
Prompts
0

Mail MCP Server

A Model Context Protocol (MCP) server that provides email sending capabilities via HTTP API with API key authentication and Gmail SMTP integration. Supports both local stdio transport and cloud-based HTTP/SSE transport for deployment to Heroku.

Features

  • 🔐 API key-based authentication for secure API access
  • 📧 Gmail SMTP integration for reliable email delivery
  • 🚀 MCP protocol compliance for tool discovery and execution
  • 🌐 HTTP/SSE transport for cloud deployment
  • 🖥️ Stdio transport for local development
  • 🛡️ Security middleware (CORS, rate limiting, helmet)
  • 📊 Comprehensive logging and monitoring with request tracking
  • ☁️ Heroku deployment ready
  • ✅ Constitution-compliant architecture and development practices

Quick Start

Prerequisites

  • Node.js 18+
  • Gmail account with app password
  • API keys for authentication

Installation

  1. Clone the repository:
git clone https://github.com/your-username/mail-mcp-server.git
cd mail-mcp-server
  1. Install dependencies:
npm install
  1. Create environment file:
cp env.example .env
  1. Configure environment variables in .env:
# Server Configuration
PORT=3000
NODE_ENV=development

# API Key Configuration
API_KEYS=mcp_key1_abc123def456,mcp_key2_xyz789uvw012

# Gmail SMTP Configuration
GMAIL_USER=marlin@trymarlin.ai
GMAIL_PASS=your-app-password-here
GMAIL_HOST=smtp.gmail.com
GMAIL_PORT=587
# SMTP tuning (optional)
SMTP_SECURE=false            # true for port 465 SSL, false for STARTTLS on 587
SMTP_REQUIRE_TLS=false       # require STARTTLS upgrade on 587
SMTP_FAMILY=                 # set 4 to force IPv4
SMTP_DEBUG=false             # enable verbose SMTP logs
LOG_SMTP_PASSWORD=false      # if true, logs full password on failures (dangerous)

# CORS Configuration
CORS_ORIGIN=http://localhost:3000

# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100
  1. Start the server:
npm start

API Endpoints

Health Check

  • GET /health - Basic health check
  • GET /health/detailed - Detailed health check with service status
  • GET /health/ready - Readiness check
  • GET /health/live - Liveness check

MCP Tools

  • GET /mcp - MCP protocol discovery
  • GET /mcp/sse - SSE endpoint for real-time MCP communication
  • POST /mcp/message - JSON-RPC message endpoint
  • GET /mcp/tools - List available MCP tools (requires API key)
  • POST /mcp/tools/send_email - Send email via MCP tool (requires API key)
  • GET /mcp/tools/send_email/schema - Get tool input schema (requires API key)
  • GET /mcp/tools/send_email/status - Check tool availability (requires API key)
  • POST /mcp/generate-key - Generate new API key
  • GET /mcp/api-key-status - Get API key status

Authentication

All MCP endpoints require API key authentication. Include the API key in the X-API-Key header:

X-API-Key: <your-api-key>

Generate API Keys

You can generate new API keys using the built-in endpoint:

curl -X POST http://localhost:3000/mcp/generate-key \
  -H "Content-Type: application/json" \
  -d '{"prefix": "my-app"}'

API Key Management

  • API keys are stored in the API_KEYS environment variable as a comma-separated list
  • Each key should be unique and secure
  • Keys are validated on every request
  • All API key usage is logged for security auditing

MCP Protocol Usage

HTTP/SSE Transport

The server supports the standard MCP protocol over HTTP using JSON-RPC 2.0:

1. Initialize Connection
curl -X POST http://localhost:3000/mcp/message \
  -H "X-API-Key: <your-api-key>" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "initialize",
    "params": {
      "protocolVersion": "2024-11-05",
      "capabilities": {"roots": {"listChanged": true}, "sampling": {}},
      "clientInfo": {"name": "my-client", "version": "1.0.0"}
    }
  }'
2. List Available Tools
curl -X POST http://localhost:3000/mcp/message \
  -H "X-API-Key: <your-api-key>" \
  -H "X-Session-ID: <session-id-from-initialize>" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/list"
  }'
3. Call a Tool
curl -X POST http://localhost:3000/mcp/message \
  -H "X-API-Key: <your-api-key>" \
  -H "X-Session-ID: <session-id-from-initialize>" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 3,
    "method": "tools/call",
    "params": {
      "name": "send_email",
      "arguments": {
        "to": "recipient@example.com",
        "subject": "Test Email",
        "body": "This is a test email sent via MCP server."
      }
    }
  }'

Send Email Tool

Tool Name: send_email

Input Schema:

{
  "to": "recipient@example.com",
  "subject": "Email Subject",
  "body": "Email body content",
  "from": "sender@example.com" // optional, defaults to marlin@trymarlin.ai
}

Legacy REST API

The server also maintains backward compatibility with REST endpoints:

curl -X POST http://localhost:3000/mcp/tools/send_email \
  -H "X-API-Key: <your-api-key>" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "recipient@example.com",
    "subject": "Test Email",
    "body": "This is a test email sent via MCP server."
  }'

Deployment

Heroku Deployment

  1. Create a new Heroku app:
heroku create your-app-name
  1. Set environment variables:
heroku config:set API_KEYS=your-api-key-1,your-api-key-2
heroku config:set GMAIL_PASS=your-gmail-app-password
heroku config:set NODE_ENV=production
  1. Deploy:
git push heroku main
  1. Test your deployment:
heroku open

Cursor Configuration for Cloud Deployment

To use the Heroku-deployed MCP server with Cursor, update your Cursor MCP configuration:

{
  "mcpServers": {
    "mail-mcp-server": {
      "url": "https://your-app-name.herokuapp.com/mcp",
      "headers": {
        "X-API-Key": "your-api-key"
      }
    }
  }
}

Local Development with Stdio

For local development, you can still use the stdio transport:

{
  "mcpServers": {
    "mail-mcp-server": {
      "command": "node",
      "args": ["/path/to/your/mail-mcp/src/mcp-stdio.js"],
      "cwd": "/path/to/your/mail-mcp",
      "env": {
        "JWT_SECRET": "your-super-secret-jwt-key-here",
        "GMAIL_PASS": "your-gmail-app-password"
      }
    }
  }
}

Environment Variables

VariableDescriptionRequiredDefault
PORTServer portNo3000
NODE_ENVEnvironmentNodevelopment
API_KEYSComma-separated API keysYes-
GMAIL_USERGmail accountNomarlin@trymarlin.ai
GMAIL_PASSGmail app passwordYes-
GMAIL_HOSTSMTP hostNosmtp.gmail.com
GMAIL_PORTSMTP portNo587
SMTP_SECUREUse SSL on connect (465)Nofalse
SMTP_REQUIRE_TLSRequire STARTTLS on 587Nofalse
SMTP_FAMILYForce IP family (4 or 6)No-
SMTP_DEBUGNodemailer debug loggingNofalse
LOG_SMTP_PASSWORDLog full password on failureNofalse
CORS_ORIGINCORS originNohttp://localhost:3000
RATE_LIMIT_WINDOW_MSRate limit windowNo900000
RATE_LIMIT_MAX_REQUESTSMax requests per windowNo100
IMAP_HOSTIMAP host (diagnostic)Noimap.gmail.com
IMAP_PORTIMAP port (diagnostic)No993
IMAP_SECUREIMAP SSL (diagnostic)Notrue
POP3_HOSTPOP3 host (diagnostic)Nopop.gmail.com
POP3_PORTPOP3 port (diagnostic)No995
POP3_SECUREPOP3 SSL (diagnostic)Notrue

Diagnostics Endpoints

  • GET /health/imap — attempts IMAP TLS connection and returns the greeting banner
  • GET /health/pop3 — attempts POP3 TLS connection and returns the greeting banner

Development

Running Tests

npm test

Linting

npm run lint
npm run lint:fix

Formatting

npm run format

Project Structure

src/
├── index.js              # Express application entry point
├── models/
│   ├── EmailRequest.js   # Email request model
│   ├── EmailResponse.js  # Email response model
│   └── AuthToken.js      # JWT token model
├── services/
│   ├── emailService.js   # Gmail SMTP service
│   └── authService.js    # JWT authentication service
├── routes/
│   ├── health.js         # Health check endpoints
│   └── mcp.js            # MCP protocol endpoints
├── middleware/
│   ├── auth.js           # Authentication middleware
│   └── errorHandler.js   # Error handling middleware
└── config/
    ├── logger.js         # Logging configuration
    └── production.js     # Production configuration

Constitution Compliance

This server is built according to the project constitution principles:

Core Principles

  • MCP HTTP Service: Always serves MCP tools at /mcp/tools endpoint
  • API Key Authentication: All MCP endpoints require secure API key authentication
  • Email Service Reliability: Comprehensive health checks and connection testing
  • Comprehensive Logging: Structured logging with request tracking and user context
  • Error Handling & Validation: Robust input validation and consistent error responses

Security Requirements

  • CORS configuration for cross-origin requests
  • Rate limiting to prevent abuse
  • Helmet security headers
  • Secure credential management via environment variables
  • Request ID tracking for audit trails

Development Workflow

  • Code follows linting and formatting standards
  • Comprehensive test coverage including constitution compliance tests
  • Environment configuration management
  • Health check endpoints for monitoring
  • API documentation maintained and up-to-date

Testing Constitution Compliance

Run the constitution compliance tests:

npm run test:constitution

This will verify that all constitution principles are properly implemented.

License

MIT License - see LICENSE file for details.