Skip to main content
Glama
TechVest-Global

Gmail MCP Server

Gmail MCP Server

An intelligent Gmail automation system using Model Context Protocol (MCP) for AI-powered email management, automated responses, and customer database integration. Features include email search, draft management, label operations, and an intelligent agent that can auto-respond to emails with human approval workflow.

Features

🔧 MCP Server Tools

  • Email Search - Query emails using Gmail search syntax

  • Email Details - Get full email content, attachments, and metadata

  • Send Emails - Send plain text or HTML emails with attachments

  • Draft Management - Create, list, update, and send drafts

  • Label Operations - Create, list, and manage Gmail labels

  • Mark as Read/Unread - Update email read status

🤖 AI Agent Capabilities

  • Automated Email Monitoring - Continuously monitors inbox for new emails

  • Intelligent Response Generation - Uses Azure OpenAI to generate contextual responses

  • Human-in-the-Loop Approval - All AI responses require human approval before sending

  • Confidence-Based Routing - Low confidence responses automatically require approval

  • Customer Database Integration - Query and update customer/order data from MySQL

  • Web-Based Approval UI - Friendly interface for reviewing and approving responses

📊 Database Integration

  • MySQL Customer Management - Store and retrieve customer information

  • Order Tracking - Manage customer orders and history

  • AI-Powered Queries - Agent can search customers, add orders, check inventory

Related MCP server: Gmail MCP Server

Prerequisites

  • Python 3.11 or higher

  • Google Cloud Project with Gmail API enabled

  • Azure OpenAI Service (for AI agent features)

  • MySQL Database (optional, for customer database features)

  • Node.js (optional, for MCP client testing)

Setup

1. Clone the Repository

git clone https://github.com/TechVest-Global/Gmail-MCP-server.git
cd Gmail-MCP-server

2. Set Up Python Environment

python -m venv myenv

# On Windows
myenv\Scripts\activate

# On macOS/Linux
source myenv/bin/activate

pip install -r requirements.txt

3. Configure Google Cloud & Gmail API

3.1 Create Google Cloud Project

  1. Go to Google Cloud Console

  2. Create a new project or select existing one

  3. Enable Gmail API:

    • Go to APIs & ServicesLibrary

    • Search for "Gmail API"

    • Click Enable

3.2 Create OAuth 2.0 Credentials

  1. Go to APIs & ServicesCredentials

  2. Click Create CredentialsOAuth client ID

  3. Configure OAuth consent screen if prompted:

    • User type: External (for testing)

    • Add your email as test user

  4. Select Desktop app as application type

  5. Download the credentials JSON file

  6. Save as credentials/credentials.json

3.3 Required Gmail API Scopes

The following scopes are configured by default:

  • https://www.googleapis.com/auth/gmail.readonly - Read emails

  • https://www.googleapis.com/auth/gmail.send - Send emails

  • https://www.googleapis.com/auth/gmail.modify - Modify emails (mark read/unread)

  • https://www.googleapis.com/auth/gmail.labels - Manage labels

4. Configure Environment Variables (Optional)

For AI agent and database features, create a .env file:

# Azure OpenAI Configuration (for AI Agent)
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
AZURE_OPENAI_API_KEY=your-api-key
AZURE_OPENAI_DEPLOYMENT=gpt-4o-mini

# MySQL Database Configuration (optional)
MYSQL_HOST=your-mysql-server.mysql.database.azure.com
MYSQL_USER=your-username
MYSQL_PASSWORD=your-password
MYSQL_DATABASE=your-database
MYSQL_PORT=3306
MYSQL_SSL_DISABLED=false

# Agent Configuration
MONITOR_INTERVAL=30
CONFIDENCE_THRESHOLD=0.8
AGENT_PORT=9000

# Google OAuth (alternative to file-based auth)
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
GOOGLE_REFRESH_TOKEN=your-refresh-token

5. Initial Authentication

Run the MCP server for the first time to authenticate:

python -m app.server

This will:

  1. Open your browser for Google OAuth

  2. Ask you to grant Gmail permissions

  3. Save credentials to credentials/token.json

  4. Token will auto-refresh when needed

Usage

MCP Server Mode

Start the MCP server to expose Gmail tools:

python -m app.server

The server communicates via stdio using the Model Context Protocol. Connect to it using an MCP client like Claude Desktop, Cline, or custom applications.

Example MCP Client Configuration (Claude Desktop)

Edit ~/Library/Application Support/Claude/claude_desktop_config.json:

{
  "mcpServers": {
    "gmail": {
      "command": "python",
      "args": ["-m", "app.server"],
      "cwd": "C:/Projects/Gmail-MCP-server",
      "env": {}
    }
  }
}

AI Agent Mode

Start the automated email responder with approval workflow:

python agent_server.py

Features:

  • Monitors inbox every 30 seconds (configurable)

  • Generates AI responses using Azure OpenAI

  • Web UI at http://localhost:9000/approvals.html

  • Approvals API at http://localhost:9000/approvals

Agent Endpoints

  • GET /health - Health check

  • GET /approvals - List pending approvals

  • POST /approvals/{message_id}/approve - Approve and send response

  • POST /approvals/{message_id}/reject - Reject proposed response

Standalone Agent with Database

Run the agent with full customer database integration:

python agent.py

This includes:

  • All email monitoring features

  • Customer database tools (add, search, update customers)

  • Order management (create, track orders)

  • Inventory checks

Project Structure

Gmail-MCP-server/
├── app/
│   ├── server.py           # Main MCP server
│   ├── gmail_auth.py       # OAuth authentication handler
│   ├── gmail_client.py     # Gmail API wrapper
│   ├── monitor.py          # Email monitoring logic
│   └── approval_store.py   # Approval workflow storage
├── agent.py                # AI agent with database integration
├── agent_server.py         # FastAPI server for agent
├── database.py             # MySQL database integration
├── email_responder.py      # Email auto-responder logic
├── credentials/
│   ├── credentials.json    # Google OAuth client credentials
│   └── token.json          # Auto-generated access token
├── chat-ui/                # Web UI for approvals
│   ├── index.html
│   ├── approvals.html
│   └── app.js
├── requirements.txt        # Python dependencies
└── README.md              # This file

Available MCP Tools

search_emails

Search for emails using Gmail query syntax.

{
  "query": "from:example@gmail.com is:unread",
  "max_results": 10,
  "include_spam_trash": false
}

get_email_details

Get complete email details including body and attachments.

{
  "message_id": "18c2f3a1b2e4d5f6"
}

send_email

Send an email (plain text or HTML).

{
  "to": "recipient@example.com",
  "subject": "Hello",
  "body": "Email content",
  "html": false,
  "cc": "cc@example.com",
  "bcc": "bcc@example.com"
}

create_draft

Create an email draft.

{
  "to": "recipient@example.com",
  "subject": "Draft Subject",
  "body": "Draft content"
}

list_labels

Get all Gmail labels.

{}

mark_as_read / mark_as_unread

Update email read status.

{
  "message_id": "18c2f3a1b2e4d5f6"
}

Troubleshooting

Common Issues

❌ Authentication Error

  • Cause: Missing or invalid credentials

  • Solution:

    • Ensure credentials/credentials.json exists

    • Delete credentials/token.json and re-authenticate

    • Check OAuth consent screen configuration

❌ Gmail API Not Enabled

  • Cause: Gmail API not enabled in Google Cloud

  • Solution: Go to Google Cloud Console → APIs & Services → Enable Gmail API

❌ Token Refresh Failed

  • Cause: Expired refresh token or revoked access

  • Solution: Delete credentials/token.json and re-authenticate

❌ ModuleNotFoundError

  • Cause: Missing dependencies

  • Solution: pip install -r requirements.txt

❌ Database Connection Error

  • Cause: MySQL credentials not configured or server unreachable

  • Solution: Check .env file for correct MySQL credentials

❌ Azure OpenAI Error

  • Cause: Invalid Azure OpenAI endpoint or API key

  • Solution: Verify credentials in .env and ensure deployment name is correct

Logging and Debugging

  • MCP server logs to stderr for debugging

  • Agent server logs to stdout

  • Check terminal output for detailed error messages

  • Use --verbose flag for detailed logging (if implemented)

Architecture

  • MCP Protocol: FastMCP framework for tool exposure

  • Gmail API: Google API Python client for Gmail operations

  • AI Agent: Agent Framework with Azure OpenAI integration

  • Web Framework: FastAPI for REST endpoints and SSE

  • Database: PyMySQL for MySQL connectivity

  • Authentication: OAuth 2.0 with automatic token refresh

Security Notes

  • Never commit credentials/credentials.json or credentials/token.json

  • Keep .env file secure and out of version control

  • Use environment variables for production deployments

  • Regularly rotate API keys and credentials

  • Review Gmail API scopes and use minimum required permissions

  • Enable 2FA on Google account for additional security

Azure Deployment

This project includes Azure deployment configurations:

Azure Functions

# Deploy to Azure Functions
.\deploy-functions.ps1

Azure App Service

# Deploy to Azure App Service
.\deploy-appservice.ps1

Azure Container Apps

# Deploy to Container Apps
.\deploy-azure.ps1

See deployment guides:

Development

Adding New MCP Tools

Add tools in app/server.py:

@mcp.tool()
async def your_new_tool(param: str) -> str:
    """Tool description"""
    # Implementation
    return result

Testing

Run tests:

pytest tests/

Code Style

Follow PEP 8 guidelines:

black .

Contributing

  1. Fork the repository

  2. Create feature branch (git checkout -b feature/your-feature)

  3. Commit changes (git commit -am 'Add new feature')

  4. Push to branch (git push origin feature/your-feature)

  5. Create Pull Request

License

MIT License - See LICENSE file for details

F
license - not found
-
quality - not tested
D
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/TechVest-Global/Gmail-MCP-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server