Initial commit: Hermes MCP - Yahoo Mail server for Claude AI
- Multi-account email support (Yahoo + self-hosted IMAP/SMTP) - MCP tools: get_profile, search_messages, read_message, list_folders, create_draft, send_email - Streamable HTTP transport with session recovery - Docker + Kubernetes deployment configuration - Express server with health endpoint 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
173
src/imap.ts
Normal file
173
src/imap.ts
Normal file
@@ -0,0 +1,173 @@
|
||||
import { ImapFlow } from 'imapflow';
|
||||
|
||||
export type Account = 'yahoo' | 'fetcherpay';
|
||||
|
||||
function getConfig(account: Account = 'yahoo') {
|
||||
if (account === 'fetcherpay') {
|
||||
return {
|
||||
host: process.env['FETCHERPAY_IMAP_HOST'] ?? 'mail.fetcherpay.com',
|
||||
port: parseInt(process.env['FETCHERPAY_IMAP_PORT'] ?? '30993'),
|
||||
secure: true,
|
||||
auth: {
|
||||
user: process.env['FETCHERPAY_EMAIL'] as string,
|
||||
pass: process.env['FETCHERPAY_PASSWORD'] as string,
|
||||
},
|
||||
tls: { rejectUnauthorized: false }, // self-signed cert on self-hosted server
|
||||
};
|
||||
}
|
||||
return {
|
||||
host: 'imap.mail.yahoo.com',
|
||||
port: 993,
|
||||
secure: true,
|
||||
auth: {
|
||||
user: process.env['YAHOO_EMAIL'] as string,
|
||||
pass: process.env['YAHOO_APP_PASSWORD'] as string,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function withClient<T>(account: Account, fn: (client: ImapFlow) => Promise<T>): Promise<T> {
|
||||
const client = new ImapFlow(getConfig(account));
|
||||
await client.connect();
|
||||
try {
|
||||
return await fn(client);
|
||||
} finally {
|
||||
await client.logout();
|
||||
}
|
||||
}
|
||||
|
||||
export interface MessageSummary {
|
||||
uid: number;
|
||||
messageId: string;
|
||||
subject: string;
|
||||
from: string;
|
||||
date: string;
|
||||
seen: boolean;
|
||||
size: number;
|
||||
}
|
||||
|
||||
export interface FullMessage {
|
||||
uid: number;
|
||||
messageId: string;
|
||||
subject: string;
|
||||
from: string;
|
||||
to: string;
|
||||
date: string;
|
||||
body: string;
|
||||
seen: boolean;
|
||||
}
|
||||
|
||||
export async function searchMessages(query: string, maxResults = 20, account: Account = 'yahoo'): Promise<MessageSummary[]> {
|
||||
return withClient(account, async (client) => {
|
||||
await client.mailboxOpen('INBOX');
|
||||
|
||||
const criteria = query
|
||||
? { or: [{ subject: query }, { from: query }] }
|
||||
: { all: true };
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const uids = await client.search(criteria as any, { uid: true });
|
||||
const uidList: number[] = Array.isArray(uids) ? uids : [];
|
||||
const recentUids = uidList.slice(-maxResults).reverse();
|
||||
|
||||
if (recentUids.length === 0) return [];
|
||||
|
||||
const messages: MessageSummary[] = [];
|
||||
for await (const msg of client.fetch(recentUids, {
|
||||
envelope: true,
|
||||
flags: true,
|
||||
size: true,
|
||||
}, { uid: true })) {
|
||||
const env = msg.envelope;
|
||||
messages.push({
|
||||
uid: msg.uid,
|
||||
messageId: env?.messageId ?? '',
|
||||
subject: env?.subject ?? '(no subject)',
|
||||
from: env?.from?.[0]
|
||||
? `${env.from[0].name ?? ''} <${env.from[0].address ?? ''}>`.trim()
|
||||
: '',
|
||||
date: env?.date?.toISOString() ?? '',
|
||||
seen: msg.flags?.has('\\Seen') ?? false,
|
||||
size: msg.size ?? 0,
|
||||
});
|
||||
}
|
||||
return messages;
|
||||
});
|
||||
}
|
||||
|
||||
export async function readMessage(uid: number, account: Account = 'yahoo'): Promise<FullMessage> {
|
||||
return withClient(account, async (client) => {
|
||||
console.log(`[imap] readMessage uid=${uid} account=${account}`);
|
||||
await client.mailboxOpen('INBOX');
|
||||
console.log(`[imap] mailbox opened, fetching uid=${uid}`);
|
||||
|
||||
let result: FullMessage | null = null;
|
||||
|
||||
for await (const msg of client.fetch([uid], {
|
||||
envelope: true,
|
||||
flags: true,
|
||||
bodyParts: ['TEXT'],
|
||||
}, { uid: true })) {
|
||||
const env = msg.envelope;
|
||||
console.log(`[imap] got msg uid=${msg.uid} subject="${env?.subject}"`);
|
||||
|
||||
const bpKeys = msg.bodyParts ? [...msg.bodyParts.keys()] : [];
|
||||
console.log(`[imap] bodyParts keys:`, JSON.stringify(bpKeys));
|
||||
|
||||
const textBuf =
|
||||
msg.bodyParts?.get('text') ??
|
||||
msg.bodyParts?.get('TEXT') ??
|
||||
msg.bodyParts?.get('1');
|
||||
console.log(`[imap] textBuf length=${textBuf ? textBuf.length : 'null'}`);
|
||||
|
||||
const rawBody = textBuf ? textBuf.toString('utf-8') : '';
|
||||
|
||||
const body = rawBody
|
||||
.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
|
||||
.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
|
||||
.replace(/<[^>]+>/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
.slice(0, 10000);
|
||||
|
||||
console.log(`[imap] body length after strip=${body.length}`);
|
||||
|
||||
result = {
|
||||
uid: msg.uid,
|
||||
messageId: env?.messageId ?? '',
|
||||
subject: env?.subject ?? '(no subject)',
|
||||
from: env?.from?.[0]
|
||||
? `${env.from[0].name ?? ''} <${env.from[0].address ?? ''}>`.trim()
|
||||
: '',
|
||||
to: env?.to?.[0]?.address ?? '',
|
||||
date: env?.date?.toISOString() ?? '',
|
||||
body,
|
||||
seen: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (!result) throw new Error(`Message UID ${uid} not found`);
|
||||
|
||||
// Mark as seen AFTER the fetch loop fully completes — calling messageFlagsAdd
|
||||
// inside the for-await loop deadlocks because the FETCH command is still active.
|
||||
console.log(`[imap] marking uid=${uid} as seen`);
|
||||
await client.messageFlagsAdd([uid], ['\\Seen'], { uid: true });
|
||||
|
||||
console.log(`[imap] readMessage done uid=${uid}`);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
export async function getProfile(account: Account = 'yahoo'): Promise<{ email: string; name: string; account: string }> {
|
||||
const email = account === 'fetcherpay'
|
||||
? (process.env['FETCHERPAY_EMAIL'] ?? '')
|
||||
: (process.env['YAHOO_EMAIL'] ?? '');
|
||||
return { email, name: email.split('@')[0], account };
|
||||
}
|
||||
|
||||
export async function listFolders(account: Account = 'yahoo'): Promise<string[]> {
|
||||
return withClient(account, async (client) => {
|
||||
const mailboxes = await client.list();
|
||||
return mailboxes.map((m) => m.path);
|
||||
});
|
||||
}
|
||||
117
src/index.ts
Normal file
117
src/index.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
import 'dotenv/config';
|
||||
import express from 'express';
|
||||
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
||||
import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
|
||||
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
||||
import {
|
||||
ListToolsRequestSchema,
|
||||
CallToolRequestSchema,
|
||||
isInitializeRequest,
|
||||
} from '@modelcontextprotocol/sdk/types.js';
|
||||
import { tools, handleToolCall } from './tools.js';
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
|
||||
function createMcpServer() {
|
||||
const server = new Server(
|
||||
{ name: 'hermes', version: '1.0.0' },
|
||||
{ capabilities: { tools: {} } }
|
||||
);
|
||||
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
|
||||
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
||||
return handleToolCall(
|
||||
request.params.name,
|
||||
(request.params.arguments ?? {}) as Record<string, unknown>
|
||||
);
|
||||
});
|
||||
return server;
|
||||
}
|
||||
|
||||
// ── NEW: Streamable HTTP transport (MCP 1.x standard) ──────────────────────
|
||||
const httpTransports = new Map<string, StreamableHTTPServerTransport>();
|
||||
|
||||
app.post('/mcp', async (req, res) => {
|
||||
const sessionId = req.headers['mcp-session-id'] as string | undefined;
|
||||
|
||||
let transport: StreamableHTTPServerTransport;
|
||||
|
||||
if (sessionId && httpTransports.has(sessionId)) {
|
||||
// Known active session — reuse it
|
||||
transport = httpTransports.get(sessionId)!;
|
||||
} else if (isInitializeRequest(req.body)) {
|
||||
// Initialize request: create a new session.
|
||||
// Handles both first-connect (no sessionId) and re-connect after pod restart
|
||||
// (stale sessionId present but not in map — we simply ignore it and issue a fresh one).
|
||||
if (sessionId) {
|
||||
console.warn(`[mcp] Stale session ${sessionId} re-initializing — pod may have restarted`);
|
||||
}
|
||||
transport = new StreamableHTTPServerTransport({
|
||||
sessionIdGenerator: () => crypto.randomUUID(),
|
||||
onsessioninitialized: (id) => { httpTransports.set(id, transport); },
|
||||
});
|
||||
transport.onclose = () => {
|
||||
if (transport.sessionId) httpTransports.delete(transport.sessionId);
|
||||
};
|
||||
const server = createMcpServer();
|
||||
await server.connect(transport);
|
||||
} else {
|
||||
// Unknown session + non-initialize request: session expired (e.g. pod restarted).
|
||||
// Return 404 so MCP clients know to re-initialize rather than keep retrying.
|
||||
console.warn(`[mcp] Unknown session ${sessionId ?? '(none)'} — returning 404`);
|
||||
res.status(404).json({ error: 'Session expired — please re-initialize' });
|
||||
return;
|
||||
}
|
||||
|
||||
await transport.handleRequest(req, res, req.body);
|
||||
});
|
||||
|
||||
app.get('/mcp', async (req, res) => {
|
||||
const sessionId = req.headers['mcp-session-id'] as string | undefined;
|
||||
if (!sessionId || !httpTransports.has(sessionId)) {
|
||||
res.status(400).json({ error: 'No active session' });
|
||||
return;
|
||||
}
|
||||
await httpTransports.get(sessionId)!.handleRequest(req, res);
|
||||
});
|
||||
|
||||
app.delete('/mcp', async (req, res) => {
|
||||
const sessionId = req.headers['mcp-session-id'] as string | undefined;
|
||||
if (sessionId && httpTransports.has(sessionId)) {
|
||||
httpTransports.delete(sessionId);
|
||||
}
|
||||
res.status(200).end();
|
||||
});
|
||||
|
||||
// ── LEGACY: SSE transport (kept for compatibility) ──────────────────────────
|
||||
const sseTransports = new Map<string, SSEServerTransport>();
|
||||
|
||||
app.get('/sse', async (req, res) => {
|
||||
const transport = new SSEServerTransport('/messages', res);
|
||||
sseTransports.set(transport.sessionId, transport);
|
||||
res.on('close', () => sseTransports.delete(transport.sessionId));
|
||||
const server = createMcpServer();
|
||||
await server.connect(transport);
|
||||
});
|
||||
|
||||
app.post('/messages', async (req, res) => {
|
||||
const sessionId = req.query.sessionId as string;
|
||||
const transport = sseTransports.get(sessionId);
|
||||
if (!transport) {
|
||||
res.status(400).json({ error: 'No active SSE session' });
|
||||
return;
|
||||
}
|
||||
await transport.handlePostMessage(req, res);
|
||||
});
|
||||
|
||||
// ── Health ──────────────────────────────────────────────────────────────────
|
||||
app.get('/health', (_req, res) => {
|
||||
res.json({ status: 'ok', service: 'hermes-mcp' });
|
||||
});
|
||||
|
||||
const PORT = process.env.PORT ?? 3456;
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Hermes MCP server running on port ${PORT}`);
|
||||
console.log(` Streamable HTTP: http://localhost:${PORT}/mcp`);
|
||||
console.log(` SSE (legacy): http://localhost:${PORT}/sse`);
|
||||
});
|
||||
97
src/smtp.ts
Normal file
97
src/smtp.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import nodemailer from 'nodemailer';
|
||||
import type { Account } from './imap.js';
|
||||
|
||||
function getSmtpTransport(account: Account = 'yahoo') {
|
||||
if (account === 'fetcherpay') {
|
||||
return nodemailer.createTransport({
|
||||
host: process.env['FETCHERPAY_SMTP_HOST'] ?? 'mail.fetcherpay.com',
|
||||
port: parseInt(process.env['FETCHERPAY_SMTP_PORT'] ?? '30587'),
|
||||
secure: false, // STARTTLS
|
||||
auth: {
|
||||
user: process.env['FETCHERPAY_EMAIL']!,
|
||||
pass: process.env['FETCHERPAY_PASSWORD']!,
|
||||
},
|
||||
tls: { rejectUnauthorized: false }, // self-signed cert
|
||||
});
|
||||
}
|
||||
return nodemailer.createTransport({
|
||||
host: 'smtp.mail.yahoo.com',
|
||||
port: 587,
|
||||
secure: false,
|
||||
auth: {
|
||||
user: process.env['YAHOO_EMAIL']!,
|
||||
pass: process.env['YAHOO_APP_PASSWORD']!,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function getSenderEmail(account: Account = 'yahoo'): string {
|
||||
return account === 'fetcherpay'
|
||||
? process.env['FETCHERPAY_EMAIL']!
|
||||
: process.env['YAHOO_EMAIL']!;
|
||||
}
|
||||
|
||||
export async function sendEmail(
|
||||
to: string,
|
||||
subject: string,
|
||||
body: string,
|
||||
account: Account = 'yahoo',
|
||||
): Promise<string> {
|
||||
const transporter = getSmtpTransport(account);
|
||||
const info = await transporter.sendMail({
|
||||
from: getSenderEmail(account),
|
||||
to,
|
||||
subject,
|
||||
text: body,
|
||||
});
|
||||
return info.messageId;
|
||||
}
|
||||
|
||||
export async function createDraft(
|
||||
to: string,
|
||||
subject: string,
|
||||
body: string,
|
||||
account: Account = 'yahoo',
|
||||
): Promise<string> {
|
||||
const { ImapFlow } = await import('imapflow');
|
||||
|
||||
const imapConfig = account === 'fetcherpay'
|
||||
? {
|
||||
host: process.env['FETCHERPAY_IMAP_HOST'] ?? 'mail.fetcherpay.com',
|
||||
port: parseInt(process.env['FETCHERPAY_IMAP_PORT'] ?? '30993'),
|
||||
secure: true,
|
||||
auth: {
|
||||
user: process.env['FETCHERPAY_EMAIL']!,
|
||||
pass: process.env['FETCHERPAY_PASSWORD']!,
|
||||
},
|
||||
tls: { rejectUnauthorized: false },
|
||||
}
|
||||
: {
|
||||
host: 'imap.mail.yahoo.com',
|
||||
port: 993,
|
||||
secure: true,
|
||||
auth: {
|
||||
user: process.env['YAHOO_EMAIL']!,
|
||||
pass: process.env['YAHOO_APP_PASSWORD']!,
|
||||
},
|
||||
};
|
||||
|
||||
const client = new ImapFlow(imapConfig);
|
||||
await client.connect();
|
||||
|
||||
const from = getSenderEmail(account);
|
||||
const rawMessage = [
|
||||
`From: ${from}`,
|
||||
`To: ${to}`,
|
||||
`Subject: ${subject}`,
|
||||
`MIME-Version: 1.0`,
|
||||
`Content-Type: text/plain; charset=UTF-8`,
|
||||
``,
|
||||
body,
|
||||
].join('\r\n');
|
||||
|
||||
await client.append('Drafts', Buffer.from(rawMessage), ['\\Draft', '\\Seen']);
|
||||
await client.logout();
|
||||
|
||||
return `Draft created: "${subject}" to ${to}`;
|
||||
}
|
||||
160
src/tools.ts
Normal file
160
src/tools.ts
Normal file
@@ -0,0 +1,160 @@
|
||||
import { Tool } from '@modelcontextprotocol/sdk/types.js';
|
||||
import { searchMessages, readMessage, getProfile, listFolders, type Account } from './imap.js';
|
||||
import { sendEmail, createDraft } from './smtp.js';
|
||||
|
||||
const ACCOUNT_PARAM = {
|
||||
account: {
|
||||
type: 'string',
|
||||
enum: ['yahoo', 'fetcherpay'],
|
||||
description: 'Which mailbox to use: "yahoo" (gheron01@yahoo.com) or "fetcherpay" (garfield.heron@fetcherpay.com). Defaults to "yahoo".',
|
||||
},
|
||||
};
|
||||
|
||||
export const tools: Tool[] = [
|
||||
{
|
||||
name: 'get_profile',
|
||||
description: 'Get the email account profile (email address and name)',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { ...ACCOUNT_PARAM },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'search_messages',
|
||||
description: 'Search email messages by keyword, sender, or subject',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
q: { type: 'string', description: 'Search query (keyword, from:email, subject:text)' },
|
||||
maxResults: { type: 'number', description: 'Max messages to return (default 20)' },
|
||||
...ACCOUNT_PARAM,
|
||||
},
|
||||
required: ['q'],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'read_message',
|
||||
description: 'Read a full email message by UID',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
uid: { type: 'number', description: 'Message UID from search results' },
|
||||
...ACCOUNT_PARAM,
|
||||
},
|
||||
required: ['uid'],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'list_folders',
|
||||
description: 'List all email folders/mailboxes',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { ...ACCOUNT_PARAM },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'create_draft',
|
||||
description: 'Create a draft email',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
to: { type: 'string', description: 'Recipient email address' },
|
||||
subject: { type: 'string', description: 'Email subject' },
|
||||
body: { type: 'string', description: 'Email body (plain text)' },
|
||||
...ACCOUNT_PARAM,
|
||||
},
|
||||
required: ['to', 'subject', 'body'],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'send_email',
|
||||
description: 'Send an email',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
to: { type: 'string', description: 'Recipient email address' },
|
||||
subject: { type: 'string', description: 'Email subject' },
|
||||
body: { type: 'string', description: 'Email body (plain text)' },
|
||||
...ACCOUNT_PARAM,
|
||||
},
|
||||
required: ['to', 'subject', 'body'],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function acct(args: Record<string, unknown>): Account {
|
||||
return (args.account as Account) ?? 'yahoo';
|
||||
}
|
||||
|
||||
export async function handleToolCall(
|
||||
name: string,
|
||||
args: Record<string, unknown>
|
||||
): Promise<{ content: Array<{ type: string; text: string }> }> {
|
||||
console.log(`[tool] ${name}`, JSON.stringify(args));
|
||||
const t0 = Date.now();
|
||||
try {
|
||||
let result: unknown;
|
||||
|
||||
switch (name) {
|
||||
case 'get_profile':
|
||||
result = await getProfile(acct(args));
|
||||
break;
|
||||
|
||||
case 'search_messages':
|
||||
result = await searchMessages(args.q as string, (args.maxResults as number) ?? 20, acct(args));
|
||||
break;
|
||||
|
||||
case 'read_message':
|
||||
result = await readMessage(args.uid as number, acct(args));
|
||||
break;
|
||||
|
||||
case 'list_folders':
|
||||
result = await listFolders(acct(args));
|
||||
break;
|
||||
|
||||
case 'create_draft':
|
||||
result = await createDraft(args.to as string, args.subject as string, args.body as string, acct(args));
|
||||
break;
|
||||
|
||||
case 'send_email':
|
||||
result = await sendEmail(args.to as string, args.subject as string, args.body as string, acct(args));
|
||||
break;
|
||||
|
||||
// Legacy Yahoo-prefixed names — keep working for any cached Claude sessions
|
||||
case 'yahoo_get_profile':
|
||||
result = await getProfile('yahoo');
|
||||
break;
|
||||
case 'yahoo_search_messages':
|
||||
result = await searchMessages(args.q as string, (args.maxResults as number) ?? 20, 'yahoo');
|
||||
break;
|
||||
case 'yahoo_read_message':
|
||||
result = await readMessage(args.uid as number, 'yahoo');
|
||||
break;
|
||||
case 'yahoo_list_folders':
|
||||
result = await listFolders('yahoo');
|
||||
break;
|
||||
case 'yahoo_create_draft':
|
||||
result = await createDraft(args.to as string, args.subject as string, args.body as string, 'yahoo');
|
||||
break;
|
||||
case 'yahoo_send_email':
|
||||
result = await sendEmail(args.to as string, args.subject as string, args.body as string, 'yahoo');
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown tool: ${name}`);
|
||||
}
|
||||
|
||||
console.log(`[tool] ${name} OK (${Date.now() - t0}ms)`);
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
||||
};
|
||||
} catch (error) {
|
||||
const msg = (error as Error).message;
|
||||
const stack = (error as Error).stack ?? '';
|
||||
console.error(`[tool] ${name} ERROR (${Date.now() - t0}ms):`, msg);
|
||||
console.error(stack);
|
||||
return {
|
||||
content: [{ type: 'text', text: `Error: ${msg}` }],
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user