Skip to main content
Glama
TechVest-Global

Gmail MCP Server

README.md
# 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

## 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
```bash
git clone https://github.com/TechVest-Global/Gmail-MCP-server.git
cd Gmail-MCP-server
```

### 2. Set Up Python Environment
```bash
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](https://console.cloud.google.com/)
2. Create a new project or select existing one
3. Enable **Gmail API**:
   - Go to **APIs & Services** → **Library**
   - Search for "Gmail API"
   - Click **Enable**

#### 3.2 Create OAuth 2.0 Credentials
1. Go to **APIs & Services** → **Credentials**
2. Click **Create Credentials** → **OAuth 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:

```bash
# 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:

```bash
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:

```bash
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`:

```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:

```bash
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:

```bash
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.
```json
{
  "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.
```json
{
  "message_id": "18c2f3a1b2e4d5f6"
}
```

### send_email
Send an email (plain text or HTML).
```json
{
  "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.
```json
{
  "to": "recipient@example.com",
  "subject": "Draft Subject",
  "body": "Draft content"
}
```

### list_labels
Get all Gmail labels.
```json
{}
```

### mark_as_read / mark_as_unread
Update email read status.
```json
{
  "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
```bash
# Deploy to Azure Functions
.\deploy-functions.ps1
```

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

### Azure Container Apps
```bash
# Deploy to Container Apps
.\deploy-azure.ps1
```

See deployment guides:
- [Azure Functions Guide](AZURE_FUNCTIONS_GUIDE.md)
- [App Service Guide](APPSERVICE_DEPLOYMENT_GUIDE.md)
- [Container Apps Guide](AZURE_CONTAINER_APPS_GUIDE.md)

## Development

### Adding New MCP Tools

Add tools in `app/server.py`:

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

### Testing

Run tests:
```bash
pytest tests/
```

### Code Style

Follow PEP 8 guidelines:
```bash
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