#!/usr/bin/env node
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';
import nodemailer from 'nodemailer';
import dotenv from 'dotenv';
dotenv.config();
function createEmailTransporter() {
const user = process.env.GMAIL_USER;
const pass = process.env.GMAIL_PASS;
if (!user || !pass) {
throw new Error('Gmail credentials not found. Set GMAIL_USER and GMAIL_PASS environment variables.');
}
return nodemailer.createTransport({
service: 'gmail',
auth: { user, pass },
});
}
async function sendEmail(to: string, subject: string, body: string) {
const transporter = createEmailTransporter();
try {
const info = await transporter.sendMail({
from: process.env.GMAIL_USER,
to,
subject,
text: body,
});
return {
success: true,
messageId: info.messageId,
};
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error',
};
}
}
async function main() {
const server = new McpServer({
name: 'gmail-mcp-server',
version: '1.0.0'
});
server.registerTool(
'send_email',
{
title: 'Send Email',
description: 'Send an email using Gmail SMTP',
inputSchema: {
to: z.string().email().describe('Recipient email address'),
subject: z.string().min(1).describe('Email subject'),
body: z.string().min(1).describe('Email body content')
},
outputSchema: {
success: z.boolean().describe('Whether email was sent successfully'),
messageId: z.string().optional().describe('Message ID from Gmail'),
error: z.string().optional().describe('Error message if failed')
}
},
async ({ to, subject, body }) => {
const result = await sendEmail(to, subject, body);
return {
content: [{
type: 'text',
text: result.success
? `Email sent to ${to}. Message ID: ${result.messageId}`
: `Failed to send email: ${result.error}`
}],
structuredContent: result
};
}
);
const transport = new StdioServerTransport();
await server.connect(transport);
}
main().catch((error) => {
console.error('Server error:', error);
process.exit(1);
});