Gmail MCP Server
by ajaysmb
README.md
# Gmail MCP Server
A **Model Context Protocol (MCP)** server that gives MCP Clients safe, local access to your Gmail account for reading, searching, and sending mail — with explicit permissions and compact, token-efficient outputs.
> **Privacy note:** The MCP server runs **locally** on your machine. Gmail data is fetched directly from Google’s APIs to your machine and is only shared with Claude when you explicitly allow a tool call.
---
## Table of Contents
- [What You Get](#what-you-get)
- [Prerequisites](#prerequisites)
- [1) Create a Google Cloud Project](#1-create-a-google-cloud-project)
- [2) Enable the Gmail API](#2-enable-the-gmail-api)
- [3) Configure the OAuth Consent Screen](#3-configure-the-oauth-consent-screen)
- [4) Create OAuth Client Credentials (Desktop App)](#4-create-oauth-client-credentials-desktop-app)
- [5) Get the Code](#5-get-the-code)
- [6) Install Python Dependencies](#6-install-python-dependencies)
- [7) First Run (Authorize and Create `token.json`)](#7-first-run-authorize-and-create-tokenjson)
- [8) Wire Into Claude Desktop (MCP Config)](#8-wire-into-claude-desktop-mcp-config)
- [9) Use It in Claude](#9-use-it-in-claude)
- [Tool Reference](#tool-reference)
- [Security Tips](#security-tips)
- [Troubleshooting](#troubleshooting)
- [Uninstall / Remove](#uninstall--remove)
- [License (MIT)](#license-mit)
---
## What You Get
- **Search & list** messages (up to 500 per call) using Gmail’s query syntax (`from:`, `subject:`, `has:attachment`, date ranges, etc.).
- **Compact summaries** (short-key JSON) to minimize LLM tokens and latency.
- **Full message fetch** with size limits, optional HTML stripping, and safe defaults.
- **Thread summaries** (first/last message, unread flag, counts).
- **Send email** (plain-text) with your explicit approval.
- **Caching & batching** under the hood to reduce API calls and speed up responses.
---
## Prerequisites
- A Google account with Gmail enabled.
- Python **3.9+** installed.
- An MCP host of your choice. This guide is configured for Claude Desktop (macOS or Windows).
---
## 1) Create a Google Cloud Project
1. Open Google Cloud Console and sign in:
`https://console.cloud.google.com/`
2. Create a project:
`https://console.cloud.google.com/projectcreate`
Give it any name (e.g., **Gmail MCP**). Note the selected project in the top bar.
---
## 2) Enable the Gmail API
1. While your project is selected, open the Gmail API page:
`https://console.cloud.google.com/apis/library/gmail.googleapis.com`
2. Click **Enable**.
---
## 3) Configure the OAuth Consent Screen
1. Go to the OAuth consent screen:
`https://console.cloud.google.com/apis/credentials/consent`
2. **User type:** choose **External**.
3. Set **Publishing status** to **Testing**.
4. Under **Test users**, click **Add users** and add the Google account(s) that will use this app (typically just your own).
5. Fill in **App name**, **User support email**, and **Developer contact information**. Save.
> Using **Testing** mode with **Test users** avoids a lengthy app verification process for personal use. The Gmail scopes requested are “sensitive,” which is expected.
---
## 4) Create OAuth Client Credentials (Desktop App)
1. Go to **Credentials**:
`https://console.cloud.google.com/apis/credentials`
2. Click **Create credentials → OAuth client ID**.
3. **Application type:** choose **Desktop app** (recommended for local tools).
4. After it’s created, click **Download JSON** and save it **next to** `gmail_mcp.py` as **`client_secret.json`**.
> **Important:** Use **Desktop app**. “Web application” often causes redirect errors for local tools.
---
## 5) Get the Code
```bash
# clone this repo (or download ZIP and extract)
git clone https://github.com/yourname/gmail-mcp.git
cd gmail-mcp
```
Place your downloaded **`client_secret.json`** in this folder (the same folder as `gmail_mcp.py`).
The app will create **`token.json`** here after your first login.
> **Do not commit secrets.** Add both files to `.gitignore`:
>
> ```
> client_secret.json
> token.json
> ```
---
## 6) Install Python Dependencies
> Install Requirements
### macOS / Linux
```bash
python3 -V
python3 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt
```
### Windows (PowerShell)
```powershell
py -3 -V
py -3 -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
pip install -r requirements.txt
```
---
## 7) First Run (Authorize and Create `token.json`)
Run the server once to complete Google sign-in and write `token.json`:
### macOS / Linux
```bash
source .venv/bin/activate
python3 gmail_mcp.py
```
### Windows (PowerShell)
```powersshell
.\.venv\Scripts\Activate.ps1
python .\gmail_mcp.py
```
- Your browser opens a Google login/consent page.
- Approve the requested scopes to allow the server to access your Gmail on your behalf.
- After success, **`token.json`** is created next to the script. Keep this file safe and private.
> If you see a **redirect_uri_mismatch** error, you likely created a **Web application** OAuth client instead of a **Desktop app**. Create a new **Desktop app** client and download it as `client_secret.json`.
You can close the terminal after you see a “Starting Gmail MCP (compact mode)… ” log message.
---
## 8) Wire Into Claude Desktop (MCP Config)
Claude Desktop reads a JSON config file named **`claude_desktop_config.json`**.
**Where is the config file?**
- **macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows:** `%APPDATA%\Claude\claude_desktop_config.json`
> In Claude Desktop you can also open this from **Settings → Developer → Edit Config**.
### Minimal configuration examples
**macOS**
```json
{
"mcpServers": {
"gmail": {
"command": "python3",
"args": ["/ABSOLUTE/PATH/TO/gmail_mcp.py"],
"env": {
"PYTHONIOENCODING": "utf-8"
}
}
}
}
```
**Windows**
```json
{
"mcpServers": {
"gmail": {
"command": "python",
"args": ["C:\\\\ABSOLUTE\\\\PATH\\\\TO\\\\gmail_mcp.py"],
"env": {
"PYTHONIOENCODING": "utf-8"
}
}
}
}
```
After saving the config, **fully quit and restart** Claude Desktop.
You should see the MCP hammer icon indicating the server is available.
---
## 9) Use It in Claude
Try prompts like:
- “Search my inbox for `subject:(invoice) newer_than:30d` and summarize the top 20.”
- “Open the full body of message ID `ABC123` with `strip_html: true`.”
- “List threads from `from:recruiter@company.com` and show unread counts.”
- “Draft an email to `alice@example.com` about Tuesday’s meeting (do not send yet).”
Claude will ask for your approval before each tool call.
---
## Tool Reference
All outputs are compact JSON (short keys, no extra whitespace) to reduce LLM tokens.
### `list_messages`
List message IDs with an optional Gmail query.
```json
{ "n": "<nextPageToken or ''>", "m": ["18c9...", "18cA..."] }
```
### `search_emails`
Search and return minimized summaries.
```json
{
"n": "<nextPageToken>",
"m": [
{
"i": "msgId",
"t": "threadId",
"f": "Name <gmail.com>",
"s": "Subject",
"d": "2025-08-23T10:01:02+05:30",
"sn": "Snippet",
"u": 0,
"sz": 12345
}
]
}
```
### `get_message_summary`
One minimized summary by message ID (same shape as above without the list).
### `get_message_full`
Full (still compact). Safe defaults: `include_html=false`, `strip_html=false`, `max_chars=4096`.
```json
{
"i": "msgId",
"t": "threadId",
"h": { "f": "From <domain>", "to": "To...", "s": "Subject", "d": "ISO-8601" },
"bt": "text body (HTML converted when strip_html=true & no text/plain present)",
"bh": "html body or '' when include_html=false",
"sn": "Gmail snippet",
"sz": 12345
}
```
### `list_threads`
List thread IDs.
```json
{ "n": "<nextPageToken>", "m": ["threadId1", "threadId2"] }
```
### `get_thread_summary`
Summary of a thread.
```json
{
"i": "threadId",
"c": 5,
"u": 1,
"s": "Subject",
"f": "FirstFrom",
"lf": "LastFrom",
"fd": "FirstDate",
"ld": "LastDate",
"lsn": "LastSnippet"
}
```
---
## Security Tips
- Keep **`client_secret.json`** and **`token.json`** **private**. Do **not** commit them to Git.
- To **revoke** access:
- Delete `token.json` and run the server again to re-consent later, **or**
- Visit Google account permissions and remove the app:
`https://myaccount.google.com/permissions`
- Scopes requested:
- `https://www.googleapis.com/auth/gmail.readonly`
- `https://www.googleapis.com/auth/gmail.send`
- `https://www.googleapis.com/auth/gmail.modify`
---
## Troubleshooting
**Redirect URI mismatch**
You probably created a **Web application** OAuth client. Make a **Desktop app** OAuth client and download it as `client_secret.json`.
**“This app is blocked” or missing scopes**
Keep the OAuth consent screen in **Testing** and add your account under **Test users**.
**403 / insufficient permissions**
Delete `token.json` and run the server again to re-consent with the latest scopes.
**Claude can’t see the server**
- Restart Claude Desktop after editing the config.
- Double-check the absolute path and JSON syntax in `claude_desktop_config.json`.
- On Windows, ensure `PYTHONIOENCODING=utf-8` is set as in the example.
**Firewall/browser issues during auth**
Allow the local browser window to open and `http://localhost:<random-port>` callbacks. Temporarily allow pop-ups if blocked.
---
## Uninstall / Remove
1. Remove the `"gmail"` block from `claude_desktop_config.json` and restart Claude Desktop.
2. Delete `token.json` and optionally `client_secret.json`.
3. Revoke the app in your Google Account permissions if desired:
`https://myaccount.google.com/permissions`
---
## License (MIT)
Copyright (c) 2025
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software **without restriction**, including without limitation the rights to **use, copy, modify, merge, publish, distribute, sublicense, and/or sell** copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in **all** copies or substantial portions of the Software.
**THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND**, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. **In no event shall the authors or copyright holders be liable** for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the Software or the use or other dealings in the Software.
This server cannot be deployed
Maintenance
ActivityInactive
ResponsivenessNo issues