Agentic AI Email Assistant MCP Server

Agentic AI Email Assistant MCP Server

Enables natural language management of Gmail through MCP tools for searching, analyzing, summarizing, drafting, and sending emails, with AI reasoning and user confirmation for actions.

Category
访问服务器

README

AI Email Assistant

An agentic AI-powered Gmail assistant that uses natural language to search, analyze, summarize, draft, and manage emails.

The system uses a Model Context Protocol (MCP) tool architecture where an AI reasoning agent dynamically selects tools and performs multi-step email workflows based on the user's request.

Features

  • Search Gmail using natural language
  • Find recent and unread emails
  • Retrieve complete email content
  • Analyze emails using Google Gemini
  • Generate prioritized email digests
  • Summarize daily emails
  • Classify emails by priority and category
  • Recommend actions for emails
  • Cache AI email analysis using SQLite
  • Generate AI-powered reply drafts
  • Compose complete emails from informal user intent
  • Reply inside existing Gmail threads
  • Send new emails
  • Mark emails as read
  • Archive emails
  • Multi-turn conversation support
  • Resolve follow-up references such as "that email" or "the first one"
  • Human confirmation before Gmail-modifying actions
  • Display email context before confirming archive or mark-as-read actions
  • Audit logging for confirmed Gmail actions
  • Streamlit chat interface
  • Timezone-aware handling of "today" using Asia/Kolkata

Architecture

The application follows an agentic tool-based workflow:

User Request
      |
      v
Streamlit Chat Interface
      |
      v
Email Assistant Agent
      |
      v
Gemini Reasoning Engine
      |
      v
MCP Tool Selection
      |
      +----------------------+----------------------+
      |                      |                      |
      v                      v                      v
 Gmail Service          AI Service          Database Service
      |                      |                      |
      v                      v                      v
 Gmail API              Gemini API               SQLite
      |                      |                      |
      +----------------------+----------------------+
                             |
                             v
                         Tool Result
                             |
                             v
                      Agent Reasoning
                             |
                  +----------+----------+
                  |                     |
                  v                     v
            Select Next Tool       Finish Request
                                        |
                                        v
                               Final User Response

The AI agent decides which MCP tool should be executed and can perform multiple tool calls to complete a request.

For deterministic operations such as timezone handling, timestamps, confirmation checks, database caching, and action validation, the application uses Python logic instead of relying on the language model.

Example Agent Workflow

User request:

Find my latest unread email and analyze it.

The agent can perform the following workflow:

1. search_email
2. get_email_content
3. analyze_email_content
4. finish

For a daily email digest:

Summarize my emails from today and show the most important ones first.

The workflow becomes:

1. generate_email_digest
2. finish

The batch digest tool avoids repeatedly calling separate tools for every email.

MCP Tools

The MCP server exposes the following tools:

search_email

Searches Gmail using Gmail search syntax.

Examples:

is:unread
from:google
subject:internship
newer_than:7d

get_email_content

Retrieves the complete content of a Gmail message using its Gmail message ID.

analyze_email_content

Uses Gemini to analyze an email and return:

  • Summary
  • Category
  • Priority
  • Recommended action

generate_email_digest

Searches matching emails, reuses cached AI analysis when available, analyzes uncached emails, and returns emails ordered by priority.

Priority order:

High
Medium
Low

draft_email_reply

Generates a professional AI reply draft for an existing email.

This tool creates a draft only and does not send the email.

mark_as_read

Marks a Gmail message as read.

Requires user confirmation before execution.

archive_gmail_email

Archives a Gmail message.

Requires user confirmation before execution.

send_gmail_email

Sends a new Gmail email.

The reasoning engine can convert an informal user instruction into a polished email subject and body before requesting confirmation.

reply_to_gmail_email

Replies to an existing email inside the same Gmail conversation thread.

Requires user confirmation before execution.

AI Reasoning Agent

The EmailAssistantAgent controls the multi-step agent loop.

For every user request, the agent:

  1. Retrieves available MCP tools.
  2. Sends the user request, available tools, previous tool history, and conversation history to the reasoning engine.
  3. Receives a structured next-action decision.
  4. Validates the selected tool and arguments.
  5. Requests confirmation for Gmail-modifying actions.
  6. Executes approved or read-only tools.
  7. Stores tool results in the current action history.
  8. Repeats the reasoning process until the request is complete or the maximum step limit is reached.

The agent uses a maximum step limit to reduce the risk of uncontrolled tool loops.

Daily Email Digest

Daily digest requests use the generate_email_digest batch MCP tool.

The workflow is:

Search Gmail
      |
      v
Retrieve Matching Emails
      |
      v
Check Gmail ID in SQLite
      |
      +----------------------+
      |                      |
      v                      v
Analysis Exists        Analysis Missing
      |                      |
      v                      v
Load Cached Analysis   Analyze with Gemini
      |                      |
      |                      v
      |                Save to SQLite
      |                      |
      +-----------+----------+
                  |
                  v
           Build Digest List
                  |
                  v
       Sort High -> Medium -> Low
                  |
                  v
          Return Email Digest

Each Gmail message is treated as a separate digest item.

The final response displays every returned email individually and preserves the priority ordering produced by the digest tool.

SQLite Analysis Cache

The application uses SQLite to cache AI-generated email analysis.

Database file:

data/emails.db

The email_analysis table stores:

  • Gmail message ID
  • Sender
  • Subject
  • Date
  • Summary
  • Category
  • Priority
  • Recommended action

The Gmail message ID is used as the primary key.

Before sending an email to Gemini for analysis, the application checks whether analysis already exists for that Gmail message ID.

If analysis exists:

Load analysis from SQLite

If analysis does not exist:

Analyze with Gemini
        |
        v
Save analysis to SQLite

This prevents repeated AI analysis of the same email and avoids duplicate analysis records.

The database caches AI analysis, not the complete Gmail email body.

Timezone-Aware "Today" Handling

The application distinguishes between:

today

and:

last 24 hours

These are not treated as the same time range.

For requests containing "today", Python calculates midnight for the current calendar date using:

Asia/Kolkata

The exact midnight time is converted to a Unix timestamp and enforced in the Gmail search query.

Example workflow:

User asks for today's emails
        |
        v
Python detects "today"
        |
        v
Calculate 00:00 Asia/Kolkata
        |
        v
Convert to Unix timestamp
        |
        v
Override AI-generated date query
        |
        v
Search Gmail from exact local midnight

For requests asking for the last 24 hours, Gmail's newer_than:1d search syntax can be used.

This keeps deterministic date and timezone calculations in Python instead of depending on the language model.

Gmail Integration

The application integrates with Gmail using the Gmail API.

The Gmail service supports:

  • Searching messages
  • Retrieving complete messages
  • Parsing email headers
  • Extracting plain-text email bodies
  • Marking messages as read
  • Archiving messages
  • Sending new emails
  • Replying inside existing Gmail threads

Email bodies are decoded from Gmail's URL-safe Base64 format.

Threaded replies use:

  • Gmail thread ID
  • Message-ID
  • In-Reply-To
  • References

This allows replies to remain inside the existing Gmail conversation thread.

Gmail Authentication

The application uses Google OAuth 2.0.

The user provides a Google OAuth desktop application credential file:

credentials.json

On the first Gmail authorization, the application opens the Google OAuth consent flow.

After successful authorization, Gmail access credentials are stored locally in:

token.json

On future runs, the stored token is reused when valid.

Sensitive authentication files are excluded from Git using .gitignore.

Gemini Integration

The application uses the Google Gemini API for:

  • Agent reasoning
  • MCP tool selection
  • Email analysis
  • Email summarization
  • Priority classification
  • Category classification
  • Recommended actions
  • Reply generation
  • New email composition
  • Final natural-language responses

The Gemini API key is loaded from an environment variable:

GEMINI_API_KEY

The key is stored locally in:

.env

The .env file is excluded from Git.

Human Confirmation and Safety

Actions that modify Gmail require explicit user confirmation.

Protected actions include:

  • Sending an email
  • Replying to an email
  • Archiving an email
  • Marking an email as read

The assistant prepares the action and displays relevant details before execution.

For a new email, the confirmation interface displays:

  • Recipient
  • Subject
  • Complete email body

For a reply, the complete reply body is displayed.

For archive and mark-as-read actions, email context such as sender, subject, and date is displayed.

The Gmail action is executed only after the user explicitly confirms it.

Audit Logging

Confirmed Gmail actions are recorded in a local audit log:

data/action_audit_log.json

Each audit record contains:

  • Timestamp
  • Tool name
  • Tool arguments
  • Success status
  • Result message

The audit log is excluded from Git because it can contain Gmail-related metadata.

Tech Stack

  • Python
  • FastMCP
  • Model Context Protocol (MCP)
  • Google Gemini API
  • Gmail API
  • Google OAuth 2.0
  • SQLite
  • Streamlit

Project Structure

AI-Email-Assistant/
├── app/
│   ├── agents/
│   │   ├── email_agent.py
│   │   └── email_assistant_agent.py
│   ├── auth/
│   │   └── gmail_auth.py
│   ├── config/
│   │   └── settings.py
│   ├── database/
│   │   └── database.py
│   ├── models/
│   │   ├── analysis.py
│   │   └── email.py
│   ├── prompts/
│   │   ├── email_prompt.py
│   │   └── reply_prompt.py
│   ├── services/
│   │   ├── agent_service.py
│   │   ├── ai_service.py
│   │   ├── audit_service.py
│   │   ├── database_service.py
│   │   └── gmail_service.py
│   └── utils/
│       └── hash.py
├── data/
│   ├── emails.db
│   └── action_audit_log.json
├── mcp_client.py
├── mcp_server.py
├── streamlit_app.py
├── requirements.txt
├── README.md
└── .gitignore

Setup

1. Clone the repository

git clone https://github.com/harshulvatsa/Agentic-AI-Email-Assistant-using-MCP.git
cd Agentic-AI-Email-Assistant-using-MCP

2. Create a virtual environment

python3 -m venv venv

Activate it on macOS or Linux:

source venv/bin/activate

Activate it on Windows:

venv\Scripts\activate

3. Install dependencies

pip install -r requirements.txt

4. Configure Gemini

Create a .env file in the project root:

GEMINI_API_KEY=your_gemini_api_key

5. Configure Gmail OAuth

Create a Google Cloud project and enable the Gmail API.

Create OAuth 2.0 credentials for a Desktop application.

Download the OAuth credential file and place it in the project root as:

credentials.json

The first Gmail request will start the Google OAuth authorization flow.

After authorization, the local Gmail token is stored as:

token.json

6. Run the application

streamlit run streamlit_app.py

Open the local Streamlit URL shown in the terminal.

Security

The following files are excluded from Git:

.env
credentials.json
token.json
data/emails.db
data/action_audit_log.json

Never commit API keys, OAuth credentials, Gmail tokens, local email analysis databases, or Gmail action audit logs to a public repository.

Example Requests

Find my latest 3 unread emails.

Analyze my latest placement email.

Draft a reply to the first email.

Send an email to example@gmail.com telling them that I completed my project.

Mark that email as read.

Archive the second email.

Summarize my emails from today and show the most important ones first.

Summarize emails from the last 24 hours.

Author

Harshul Vatsa

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选