Skip to main content
Glama
TannaPrasanthkumar

Gmail MCP Server

README.md
# Gmail MCP AI Integration

An intelligent Gmail assistant powered by Azure OpenAI and the Model Context Protocol (MCP). This project enables AI agents to interact with Gmail through a standardized MCP server interface, allowing for natural language email management and automation.

## Features

- **MCP Server for Gmail**
  - Search emails with natural language queries
  - Read email content with full metadata
  - Send emails with attachments
  - Mark emails as read/unread
  - Delete and trash management
  - Label operations
  - Draft management

- **AI Agent Integration**
  - Azure OpenAI-powered assistant using Agent Framework
  - Natural language email understanding
  - Context-aware responses
  - Efficient inbox management

- **Authentication**
  - OAuth 2.0 Gmail authentication
  - Environment variable support for Azure deployments
  - Secure credential management
  - Refresh token handling

## Prerequisites

- Python 3.11 or higher
- Google Cloud account with Gmail API enabled
- Azure OpenAI Service (for agent functionality)
- Required OAuth 2.0 credentials from Google Cloud Console

## Setup

### 1. Clone the repository
```bash
git clone <repository-url>
cd Gmail-MCP-AI-Integration
```

### 2. Set up Python environment
```bash
python -m venv venv
venv\Scripts\activate  # On Windows
# source venv/bin/activate  # On macOS/Linux
pip install -r requirements.txt
```

### 3. Configure Gmail API

#### Step-by-step guide to get Gmail API credentials:

1. **Go to [Google Cloud Console](https://console.cloud.google.com/)**

2. **Create or Select a Project**
   - Click the project dropdown at the top
   - Click "New Project" or select existing project
   - Enter a project name (e.g., "Gmail MCP Server")
   - Click "Create"

3. **Enable the Gmail API**
   - In the left sidebar, go to **APIs & Services** → **Library**
   - Search for "Gmail API"
   - Click on "Gmail API" in the results
   - Click the **Enable** button

4. **Configure OAuth Consent Screen** (First-time setup)
   - Go to **APIs & Services** → **OAuth consent screen**
   - Select **External** user type
   - Click **Create**
   - Fill in required fields:
     - App name: "Gmail MCP Server"
     - User support email: Your email
     - Developer contact: Your email
   - Click **Save and Continue**
   - On Scopes page, click **Save and Continue**
   - On Test users page, add your Gmail address, click **Save and Continue**

5. **Create OAuth 2.0 Credentials**
   - Go to **APIs & Services** → **Credentials**
   - Click **+ Create Credentials** → **OAuth client ID**
   - Choose **Application type**: **Desktop app**
   - Name it: "Gmail MCP Desktop Client"
   - Click **Create**
   - Click **Download JSON** (or click the download icon for your credential)
   - Save the file as `credentials.json`

6. **Place credentials.json in your project**
   ```bash
   # Create credentials folder if it doesn't exist
   mkdir credentials
   
   # Move downloaded file to credentials/credentials.json
   # Windows: copy Downloads\credentials.json credentials\credentials.json
   # Linux/Mac: mv ~/Downloads/credentials.json credentials/credentials.json
   ```

> **Note**: On first run, a browser window will open asking you to authorize the application. After authorization, a `token.json` file will be created automatically.

### 4. Configure Azure OpenAI (Optional, for AI Agent)

If you want to use the AI agent functionality, follow these steps to get Azure OpenAI credentials:

#### Step-by-step guide to get Azure OpenAI credentials:

1. **Go to [Azure Portal](https://portal.azure.com)**
   - Sign in with your Microsoft account
   - If you don't have an account, click "Create one" (Free account available)

2. **Create Azure OpenAI Resource**
   - Click **Create a resource** (+ icon in top left)
   - Search for **"Azure OpenAI"**
   - Click **Create** → **Azure OpenAI**
   - Fill in the required fields:
     - **Subscription**: Select your Azure subscription
     - **Resource group**: Create new or select existing (e.g., "gmail-mcp-rg")
     - **Region**: Choose a region (e.g., "East US", "West Europe")
     - **Name**: Enter a unique name (e.g., "gmail-mcp-openai")
     - **Pricing tier**: Select Standard S0
   - Click **Review + Create** → **Create**
   - Wait for deployment (usually 1-2 minutes)

3. **Get Endpoint and API Key**
   - After deployment, click **Go to resource**
   - In the left menu, click **Keys and Endpoint**
   - Copy these values:
     - **Endpoint**: Should look like `https://your-resource.openai.azure.com/`
     - **Key 1**: Your API key (long string of characters)

4. **Deploy a Model**
   - In the left menu, click **Model deployments** or go to [Azure OpenAI Studio](https://oai.azure.com)
   - Click **Create new deployment** or **Deploy model**
   - Select a model:
     - **gpt-4**: Most capable, higher cost
     - **gpt-4-turbo**: Fast and capable
     - **gpt-4.1-mini**: Fast, cost-effective (recommended for testing)
     - **gpt-35-turbo**: Fastest, lowest cost
   - Give it a deployment name (e.g., "gpt-4-mini")
   - Click **Create**

5. **Create and configure .env file**
   ```bash
   # Copy the example file
   copy .env.example .env
   ```
   
   Edit `.env` and add your Azure OpenAI credentials:
   ```env
   AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
   AZURE_OPENAI_API_KEY=your_actual_api_key_here
   AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4-mini
   ```

> **Cost Note**: Azure OpenAI is a paid service. Check [Azure OpenAI Pricing](https://azure.microsoft.com/en-us/pricing/details/cognitive-services/openai-service/) for rates. New accounts get $200 free credit for 30 days.

### 5. Run the MCP Server

Start the Gmail MCP server:

```bash
python app/server.py
```

The server will:
- Authenticate with Gmail (browser window will open on first run)
- Start listening for MCP protocol messages via STDIO
- Log status messages to stderr

### 6. Test the Server

Use the provided test client:

```bash
python mcp_client.py
```

This will:
- Connect to the MCP server
- Test basic operations (search, read emails)
- Display results

## Usage

### Using the MCP Server

The server exposes the following MCP tools:

#### `search_emails`
Search for emails using Gmail query syntax.

```json
{
  "query": "from:someone@example.com",
  "max_results": 10,
  "include_spam_trash": false
}
```

#### `get_email`
Get detailed information about a specific email.

```json
{
  "message_id": "abc123..."
}
```

#### `send_email`
Send a new email with optional attachments.

```json
{
  "to": "recipient@example.com",
  "subject": "Hello",
  "body": "Message content",
  "cc": "cc@example.com",
  "bcc": "bcc@example.com",
  "attachments": [{"filename": "doc.pdf", "content": "base64..."}]
}
```

#### `mark_as_read` / `mark_as_unread`
Change read status of emails.

```json
{
  "message_ids": ["id1", "id2"]
}
```

#### `delete_email` / `trash_email` / `untrash_email`
Manage email deletion and trash.

```json
{
  "message_id": "abc123..."
}
```

#### `list_labels`
Get all Gmail labels.

```json
{}
```

#### `add_label` / `remove_label`
Manage email labels.

```json
{
  "message_ids": ["id1", "id2"],
  "label_ids": ["Label_1"]
}
```

#### `create_draft` / `list_drafts` / `send_draft` / `delete_draft`
Manage email drafts.

### Using with Claude Desktop

Add to your Claude Desktop config (`claude_desktop_config.json`):

```json
{
  "mcpServers": {
    "gmail": {
      "command": "python",
      "args": ["C:/Projects/Gmail-MCP-AI-Integration/app/server.py"]
    }
  }
}
```

Then restart Claude Desktop. The Gmail tools will be available in conversations.

### Using the AI Agent

Run the agent directly:

```bash
python app/agent.py
```

The agent uses Azure OpenAI and can interact with Gmail through the MCP protocol.

## Project Structure

```
Gmail-MCP-AI-Integration/
├── app/
│   ├── __init__.py
│   ├── agent.py           # AI agent using Agent Framework
│   ├── gmail_auth.py      # OAuth 2.0 authentication
│   ├── gmail_client.py    # Gmail API wrapper
│   └── server.py          # MCP server implementation
├── credentials/
│   ├── credentials.json   # OAuth credentials (not in repo)
│   └── token.json        # Access token (auto-generated)
├── mcp_client.py          # Test client for MCP protocol
├── test_*.py             # Various test scripts
├── requirements.txt       # Python dependencies
└── README.md             # This file
```

## Troubleshooting

### Common Issues

**❌ Authentication Failed**
- **Cause:** Missing or invalid credentials.json
- **Solution:** 
  - Ensure credentials.json is in the credentials/ folder
  - Verify it's for a Desktop application type
  - Re-download from Google Cloud Console if needed

**❌ "Access blocked: This app's request is invalid"**
- **Cause:** Incorrect OAuth 2.0 setup
- **Solution:**
  - Make sure you created a "Desktop application" credential type
  - Check that Gmail API is enabled in your project

**❌ Server Not Responding**
- **Cause:** Server initialization failed
- **Solution:**
  - Check stderr output for error messages
  - Verify all dependencies are installed
  - Ensure credentials are properly configured

**❌ Token Expired**
- **Cause:** Refresh token is invalid or expired
- **Solution:**
  - Delete `credentials/token.json`
  - Re-run the server to re-authenticate

**❌ ModuleNotFoundError**
- **Cause:** Missing dependencies
- **Solution:** `pip install -r requirements.txt`

### Environment Variables for Azure Deployment

For production deployments (e.g., Azure), you can use environment variables:

```env
GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secret
GOOGLE_REFRESH_TOKEN=your_refresh_token
```

The server will automatically detect and use these instead of file-based authentication.

## Architecture

- **MCP Protocol**: Standardized interface for AI tools
- **FastMCP**: Framework for building MCP servers
- **Gmail API**: Official Google API for email operations
- **Agent Framework**: Azure's framework for building AI agents
- **Azure OpenAI**: LLM for natural language understanding

## Security Notes

- Never commit `credentials.json` or `token.json` to version control
- Use environment variables for production deployments
- Limit OAuth scopes to only what's needed
- Regularly review and rotate credentials
- Use Azure Key Vault for production secrets

## Testing

Run the test suite:

```bash
# Test MCP protocol
python test_mcp_protocol.py

# Test server functionality
python test_server.py

# Test individual features
python test_functionality.py
```

## Contributing

1. Fork the repository
2. Create feature branch (`git checkout -b feature/name`)
3. Commit your changes (`git commit -am 'Add feature'`)
4. Push to the branch (`git push origin feature/name`)
5. Create Pull Request

## License

This project is provided as-is for educational and development purposes.

## Acknowledgments

- Built with [FastMCP](https://github.com/jlowin/fastmcp) framework
- Uses [Agent Framework](https://github.com/microsoft/agent-framework) for Azure AI integration
- Powered by [Gmail API](https://developers.google.com/gmail/api)
- Model Context Protocol by Anthropic

## Resources

- [MCP Documentation](https://modelcontextprotocol.io/)
- [Gmail API Documentation](https://developers.google.com/gmail/api/guides)
- [Azure OpenAI Service](https://azure.microsoft.com/en-us/products/ai-services/openai-service)
- [FastMCP GitHub](https://github.com/jlowin/fastmcp)

## Support

For issues and questions:
- Check the [Troubleshooting](#troubleshooting) section
- Review test results in [TEST_RESULTS.md](TEST_RESULTS.md)
- Open an issue on GitHub
3. Commit changes (`git commit -am 'Add feature'`)
4. Push branch (`git push origin feature/name`)
5. Create Pull Request

## License

[Your License Type] - See LICENSE file for details

Maintenance

ActivityInactive
ResponsivenessNo issues