AI邮件分类工具

一款基于AI的邮件清理应用,自动分类和归档Gmail/Yahoo邮件,采用MCP协议分离前后端。

  • by leostahlkim
  • TypeScript
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 leostahlkim/mcp-mail-integration

使用说明

电子邮件清理器-MCP邮件集成

一款基于人工智能的电子邮件清理应用程序,通过自动分类和归档电子邮件来帮助您组织收件箱。使用模型上下文协议(MCP)构建,实现了AI后端和web界面之间的清晰分离。

目录


这个应用程序做什么?

此应用程序连接到您的Gmail或Yahoo电子邮件帐户,并使用Claude AI将您的电子邮件分类为以下类别:

  • 垃圾邮件 -未经请求的可疑电子邮件
  • 营销 -来自公司的促销电子邮件
  • 通讯 -定期订阅时事通讯
  • 社交 -社交媒体通知
  • 促销的 -销售、折扣、优惠
  • 不相关的 -无需任何操作的自动通知
  • 重要 -需要关注的个人/工作电子邮件

根据人工智能的置信水平,电子邮件可以是:

  • 自动存档 (高置信度垃圾邮件)
  • 发送到审核队列 (中等信心,由你决定)
  • 保存在收件箱中 (低置信度或重要)

架构概述

该应用程序由三个相互通信的主要部分组成:

┌─────────────────────┐         HTTP/JSON-RPC         ┌─────────────────────┐
│                     │◄────────────────────────────►│                     │
│   Web App (UI)      │                              │   MCP Server        │
│   Next.js           │                              │   Node.js           │
│   Port 3000         │                              │   Port 3001         │
│                     │                              │                     │
└─────────────────────┘                              └──────────┬──────────┘
                                                                │
                                                                │ OAuth2 + API calls
                                                                │
                                              ┌─────────────────┴─────────────────┐
                                              │                                   │
                                              ▼                                   ▼
                                    ┌─────────────────┐                 ┌─────────────────┐
                                    │  Gmail / Yahoo  │                 │   Claude API    │
                                    │  Email APIs     │                 │   (Anthropic)   │
                                    └─────────────────┘                 └─────────────────┘

为什么是这种架构?

  1. MCP服务器:充当“后端”,公开web应用程序可以调用的“工具”(功能)。这将所有敏感逻辑(OAuth令牌、API密钥)保留在服务器端。

  2. 网络应用:一个用户友好的界面,调用MCP服务器的工具来获取电子邮件、触发分类和存档消息。

  3. 关注点分离:这个网络应用程序不知道如何与Gmail或Claude对话,它只会调用以下工具 emails_fetch 或 emails_classify这使得系统模块化和安全。


项目结构

这是一个 单体仓库 (一个存储库中的多个包)由管理 pnpm工作区 和 涡轮仓库.

mcp-mail-integration/
│
├── packages/                    # Shared libraries and backend
│   │
│   ├── shared/                  # Shared code used by both server and webapp
│   │   ├── package.json
│   │   ├── tsconfig.json
│   │   └── src/
│   │       ├── index.ts         # Exports everything from this package
│   │       └── schemas/         # Zod schemas (validation + TypeScript types)
│   │           ├── provider.schema.ts      # OAuth & auth types
│   │           ├── email.schema.ts         # Email data types
│   │           └── classification.schema.ts # Classification types
│   │
│   └── mcp-server/              # The MCP server (backend)
│       ├── package.json
│       ├── tsconfig.json
│       └── src/
│           ├── index.ts         # Entry point - starts Express server
│           ├── server.ts        # MCP server setup & tool registration
│           │
│           ├── tools/           # MCP tool definitions (what the server can do)
│           │   ├── auth.tools.ts      # OAuth flow tools
│           │   ├── email.tools.ts     # Email fetch/archive tools
│           │   └── classify.tools.ts  # Classification tool
│           │
│           ├── providers/       # Email provider implementations
│           │   ├── index.ts           # Provider factory
│           │   ├── gmail/
│           │   │   └── gmail.client.ts    # Gmail API integration
│           │   └── yahoo/
│           │       └── yahoo.client.ts    # Yahoo API integration
│           │
│           ├── services/        # Business logic services
│           │   └── classification.service.ts  # Claude AI classification
│           │
│           └── storage/         # Data persistence
│               └── token.storage.ts   # Encrypted SQLite for OAuth tokens
│
├── apps/                        # Applications
│   │
│   └── webapp/                  # Next.js web application (frontend)
│       ├── package.json
│       ├── tsconfig.json
│       ├── next.config.js       # Next.js configuration
│       ├── tailwind.config.js   # Tailwind CSS configuration
│       ├── postcss.config.js    # PostCSS configuration
│       │
│       └── src/
│           ├── app/             # Next.js App Router pages
│           │   ├── layout.tsx         # Root layout (applies to all pages)
│           │   ├── page.tsx           # Home page (/)
│           │   ├── providers.tsx      # React Query provider setup
│           │   ├── globals.css        # Global styles & CSS variables
│           │   │
│           │   ├── auth/
│           │   │   ├── connect/
│           │   │   │   └── page.tsx   # Provider selection (/auth/connect)
│           │   │   └── callback/
│           │   │       └── page.tsx   # OAuth callback handler (/auth/callback)
│           │   │
│           │   ├── inbox/
│           │   │   └── page.tsx       # Email list view (/inbox)
│           │   │
│           │   └── review/
│           │       └── page.tsx       # Review queue (/review)
│           │
│           ├── components/      # Reusable React components
│           │   ├── ui/                # Generic UI components (shadcn/ui style)
│           │   │   ├── button.tsx
│           │   │   ├── card.tsx
│           │   │   ├── checkbox.tsx
│           │   │   └── badge.tsx
│           │   │
│           │   ├── email/             # Email-specific components
│           │   │   ├── email-list.tsx       # Email list with toolbar
│           │   │   └── email-list-item.tsx  # Individual email row
│           │   │
│           │   └── review/            # Review queue components
│           │       ├── review-queue.tsx     # Review queue container
│           │       └── review-card.tsx      # Individual review item
│           │
│           ├── stores/          # Zustand state management
│           │   ├── auth.store.ts      # Authentication state
│           │   └── email.store.ts     # Email & classification state
│           │
│           └── lib/             # Utility functions
│               ├── utils.ts           # General utilities (cn for classNames)
│               ├── date-utils.ts      # Date formatting
│               └── mcp-client.ts      # MCP server communication
│
├── package.json                 # Root package.json (workspace scripts)
├── pnpm-workspace.yaml          # Defines which folders are packages
├── turbo.json                   # Turborepo build configuration
├── tsconfig.base.json           # Shared TypeScript configuration
├── .env.example                 # Example environment variables
└── .gitignore                   # Git ignore rules

运作原理

1.共享包(packages/shared)

这个包裹包含 Zod模式 它们定义了整个应用程序中使用的数据的形状。Zod给了我们两个:

  • 运行时验证:检查数据是否与预期形状匹配
  • TypeScript类型:自动生成类型以确保类型安全

示例来自 email.schema.ts:

export const EmailSummarySchema = z.object({
  id: z.string(),
  subject: z.string(),
  from: EmailAddressSchema,
  date: z.string().datetime(),
  // ... more fields
});

// This generates a TypeScript type automatically
export type EmailSummary = z.infer<typeof EmailSummarySchema>;

2.MCP服务器(packages/mcp-server)

MCP服务器公开 工具 可以通过HTTP调用。将工具视为API端点,但遵循MCP协议。

入口点(index.ts):

  • 创建Express服务器
  • 为web应用程序设置CORS
  • 处理MCP请求 /mcp 端点
  • 管理有状态连接的会话ID

服务器设置(server.ts):

  • 创建MCP服务器实例
  • 使用模式和处理程序注册所有工具

工具(tools/): 每个工具都有:

  • A. 名字 (例如。, emails_fetch)
  • A. 描述 (它做什么)
  • 一 输入模式 (它接受哪些参数)
  • A. 处理函数 (实际逻辑)

供应商(providers/): 以下是与电子邮件服务对话的实际实现:

  • gmail.client.ts:使用谷歌的 googleapis 图书馆
  • yahoo.client.ts:使用雅虎的REST API

每个提供者处理:

  • OAuth URL生成
  • 代币兑换
  • 令牌刷新
  • 电子邮件提取
  • 邮件归档

服务项目(services/):

  • classification.service.ts:向Claude API发送电子邮件,并提供精心编制的提示,解析响应,并确定要采取的操作。

存储(storage/):

  • token.storage.ts:将OAuth令牌存储在SQLite中,使用AES-256-GCM加密。这使令牌在静止时保持安全。

3.网络应用程序(apps/webapp)

使用App Router的Next.js 14应用程序。

页面(app/):

  • / -显示已连接帐户的主页
  • /auth/connect -选择Gmail或Yahoo进行连接
  • /auth/callback -处理OAuth重定向
  • /inbox -主电子邮件列表视图
  • /review -不确定分类的审查队列

国家管理(stores/): 使用Zustand实现简单、轻便的状态:

  • auth.store.ts:跟踪连接的帐户,处理身份验证流
  • email.store.ts:管理电子邮件列表、选择、分类、审核队列

MCP客户端(lib/mcp-client.ts): 一种包装:

  • 向MCP服务器发送JSON-RPC请求
  • 维护会话ID以进行有状态通信
  • 提供类型安全功能,如 mcpTools.emailsFetch()

组件:

  • ui/:通用、可重复使用的组件(按钮、卡片等)
  • email/:电子邮件特定组件(列表、列表项)
  • review/:查看队列组件

安装说明

先决条件

  • Node.js 18或更高版本
  • pnpm(如果缺失,将安装)

1.安装依赖项

# Install pnpm globally if you don't have it
npm install -g pnpm

# Install all dependencies
pnpm install

2.设置环境变量

# Copy the example file
cp .env.example .env

# Edit .env with your values (see Environment Variables section)

3.设置Gmail OAuth(如果使用Gmail)

  1. 首选 Google 云控制台
  2. 创建一个新项目
  3. 启用Gmail API
  4. 配置OAuth同意屏幕
  5. 创建OAuth 2.0凭据(Web应用程序)
  6. 添加 http://localhost:3000/auth/callback?provider=gmail 作为授权重定向URI
  7. 将客户端ID和客户端密码复制到 .env

4.设置雅虎OAuth(如果使用雅虎)

  1. 首选 雅虎开发者网络
  2. 创建具有Mail API访问权限的应用程序
  3. 获取客户端ID和客户端密码
  4. 添加重定向URI: http://localhost:3000/auth/callback?provider=yahoo

5.获取Anthropic API密钥

  1. 首选 Anthropic 控制台
  2. 创建API密钥
  3. 增添 .env 作为 ANTHROPIC_API_KEY

运行应用程序

发展模式

# Start both MCP server and web app
pnpm dev

这运行:

  • MCP服务器位于 http://localhost:3001
  • Web应用程序位于 http://localhost:3000

生产建设

# Build all packages
pnpm build

# Start the MCP server
pnpm -F @mcp-mail/server start

# In another terminal, start the web app
pnpm -F @mcp-mail/webapp start

环境变量

创建一个 .env 根目录中的文件:

# Gmail OAuth Credentials
# Get these from Google Cloud Console
GMAIL_CLIENT_ID=your-gmail-client-id.apps.googleusercontent.com
GMAIL_CLIENT_SECRET=your-gmail-client-secret
GMAIL_REDIRECT_URI=http://localhost:3000/auth/callback?provider=gmail

# Yahoo OAuth Credentials
# Get these from Yahoo Developer Network
YAHOO_CLIENT_ID=your-yahoo-client-id
YAHOO_CLIENT_SECRET=your-yahoo-client-secret
YAHOO_REDIRECT_URI=http://localhost:3000/auth/callback?provider=yahoo

# Anthropic API Key
# Get this from console.anthropic.com
ANTHROPIC_API_KEY=sk-ant-your-api-key

# MCP Server Port
MCP_SERVER_PORT=3001

# Token Encryption Key
# Generate a random string for encrypting stored OAuth tokens
# You can use: openssl rand -hex 32
TOKEN_ENCRYPTION_KEY=your-random-encryption-key

MCP工具参考

以下是MCP服务器公开的工具:

身份验证工具

工具 描述 输入
auth_initiate 启动OAuth流程,返回URL以重定向用户 { provider: "gmail" | "yahoo" }
auth_callback 用OAuth代码交换令牌 { provider, code, state }
auth_status 列出所有已连接的帐户 { provider?: "gmail" | "yahoo" }

电子邮件工具

工具 描述 输入
emails_fetch 从收件箱获取电子邮件 { provider, accountEmail, maxResults?, pageToken?, query? }
email_get_content 获取完整的电子邮件正文 { provider, accountEmail, emailId }
emails_archive 存档电子邮件(从收件箱中删除) { provider, accountEmail, emailIds[] }

分类工具

工具 描述 输入
emails_classify 使用AI对电子邮件进行分类 { provider, accountEmail, emailIds[] }

分类逻辑

分类服务使用这些置信阈值:

置信水平 范围 行动
高 >=85% 自动存档(无需用户审核)
中等 60%-84% 添加到评论队列(用户决定)
低 <60% 保留在收件箱中(可能很重要)

归档的类别

这些类别被认为是“可归档的”(不重要):

  • 垃圾邮件
  • 营销
  • 通讯
  • 社交
  • 促销的
  • 无关的

这 important 类别从不自动存档。

分类提示

AI被指示 怀疑的 -它假设大多数自动电子邮件并不重要。这有助于捕获更多的垃圾邮件,同时对潜在的重要电子邮件保持保守。


技术栈概述

组件 技术
单体仓库 pnpm工作区+Turborepo
语言 TypeScript
验证 佐德
MCP服务器 @modelcontextprotocol/sdk+Express
电子邮件API 谷歌邮箱(Gmail)、fetch(雅虎)
人工智能 @anthropic ai/sdk(克劳德)
令牌存储 better平方3(加密)
Web框架 Next.js 14(应用路由器)
样式 顺风CSS
UI组件 Radix UI图元
状态管理 状态
数据获取 TanStack查询

故障排除

“TOKEN_ENCRYPTION_KEY环境变量是必需的”

确保您已设置 TOKEN_ENCRYPTION_KEY 在你的 .env 文件。

OAuth重定向错误

  • 检查您的重定向URI是否与Google/Yahoo控制台中配置的完全匹配
  • 确保您正在使用 http://localhost:3000 (不是 127.0.0.1)

“找不到模块'@mcp-mail/shared'”

跑 pnpm build 首先构建所有包。

电子邮件未加载

  • 检查浏览器控制台是否有错误
  • 验证MCP服务器是否在端口3001上运行
  • 检查OAuth令牌是否未过期

许可证

麻省理工学院