Skip to main content
Glama

Gmail MCP Server

A Model Context Protocol (MCP) server for Gmail & Google Calendar integration with Claude Desktop, enabling intelligent, context-aware interactions with your email.

🌟 Features

  • Deep Email Analysis: Provides comprehensive context from entire conversation threads

  • Context-Aware Responses: Generates responses considering full communication history

  • Intelligent Action Suggestions: Analyzes email content for calendar events, tasks, and follow-ups

  • Calendar Integration: Detects events in emails and creates calendar entries with natural language support

  • Advanced Search: Searches across entire email history with semantic understanding

  • Personalization: Adapts to your communication style with specific contacts

Related MCP server: Gmail MCP Server

🚀 Getting Started

Prerequisites

  • Python 3.10+

  • A Google Cloud Platform account with Gmail API and Google Calendar API (optional) enabled

  • OAuth 2.0 credentials for the Gmail API and Google Calendar API (optional)

  • Claude Desktop with MCP support (currently only LLM interface to support MCP)

Installation

Installing via Smithery

To install Gmail Integration Server for Claude Desktop automatically via Smithery:

npx -y @smithery/cli install @bastienchabal/gmail-mcp --client claude

Installing Manually

  1. Clone this repository:

    git clone https://github.com/bastienchabal/gmail-mcp.git
    cd gmail-mcp
  2. Set up a virtual environment using uv:

    pip install uv
    uv venv
    source .venv/bin/activate  # On Windows: .venv\Scripts\activate
  3. Install dependencies:

    uv pip install -e .

⚙️ Configuration

Step 1: Authenticate with Google

  1. Go to the Google Cloud Console

  2. Create a new project or select an existing one

  3. Enable Google APIs:

  4. Configure the OAuth consent screen:

    • Select "External" user type

    • Add your email as a test user

    • Add all the scopes of Gmail and Calendar

  5. Create OAuth 2.0 credentials:

    • Choose "Desktop app" as the application type

    • Download the JSON credentials file and copy the Client ID and Client Secret

Step 2: Configure Claude Desktop

  1. Create or edit the claude_desktop_config.json file in /Users/<username>/Library/Application Support/Claude

  2. Add the following configuration, replacing the placeholders with your actual values:

{
  "mcpServers": {
    "gmail-mcp": {
      "command": "/<absolute-path>/gmail-mcp/.venv/bin/mcp",
      "args": [
        "run",
        "/<absolute-path>/gmail-mcp/gmail_mcp/main.py:mcp"
      ],
      "cwd": "/<absolute-path>/gmail-mcp",
      "env": {
        "PYTHONPATH": "/<absolute-path>/gmail-mcp",
        "CONFIG_FILE_PATH": "/<absolute-path>/gmail-mcp/config.yaml",
        "GOOGLE_CLIENT_ID": "<your-client-id>",
        "GOOGLE_CLIENT_SECRET": "<your-client-secret>",
        "TOKEN_ENCRYPTION_KEY": "<generate-a-random-key>"
      }
    }
  }
}

Notes:

  • Replace <absolute-path> with the actual path to your gmail-mcp directory

  • Replace <your-client-id> and <your-client-secret> with your Google OAuth credentials (previously generated in the json file)

  • Optional : Generate a random encryption key with: python -c "import os; from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"

The configuration is designed to keep sensitive data (client ID, client secret, and encryption key) in the Claude Desktop configuration file, while non-sensitive settings are stored in the config.yaml file included in the repository.

Step 3: Use Claude Desktop

  1. Open Claude Desktop

  2. Type a prompt like: "Please retrieve my last email"

  3. Claude should automatically connect to the MCP server and ask you to authenticate to your Gmail account (creating the file tokens.json)

❓ Troubleshooting

Important Note on MCP

If Claude Desktop doesn't connect automatically (i.e. you do not see the tool icon underneath the prompt input), you can try:

  • Restarting Claude Desktop

  • Asking Claude to "Use the Gmail MCP server"

  • Login to Gmail manually using one of these methods:

Important Note on Authentication

  1. Authentication Problems:

    • Run python debug/auth_test.py to test the authentication process with detailed feedback

    • Check that the token file exists at the project root

    • Verify that your Google Cloud Console project has the correct redirect URI configured

    • Make sure all required scopes are added to your OAuth consent screen

    • If you see "Scope has changed" errors, ensure that the openid scope is included in your OAuth consent screen

    • If you see "redirect_uri_mismatch" errors, add the exact URI shown in the error message to your authorized redirect URIs in Google Cloud Console

    • If the callback page doesn't load or process properly, check if port 8000 is already in use by another application

  2. Calendar API Issues:

    • Make sure you've enabled the Calendar API in Google Cloud Console

    • Check that you've granted all the necessary scopes during authentication

    • Run python debug/reauth_calendar.py to re-authenticate with Calendar API scopes

    • Verify that CALENDAR_API_ENABLED is set to true in your environment variables

Important Note on Calendar Integration

Calendar integration can be turned off in the configuration file. If you've previously authenticated with the Gmail MCP server and are now enabling Calendar integration, you'll need to re-authenticate to grant the additional Calendar API scopes. You can do this by:

  1. Deleting the existing tokens.json file (if present, either at projet root or in ~/Users/<username/>gmail_mcp_tokens/tokens.json)

  2. Restarting the MCP server

  3. Following the authentication process again

👤 Usage

The Gmail MCP provides powerful, context-aware tools for managing your emails and calendar:

Email Management

  • Email Overview: Get a comprehensive view of your inbox with counts and recent emails

  • Advanced Search: Use Gmail's powerful search syntax to find specific emails

  • Detailed Email Analysis: View emails with full context, including thread history and sender information

Context-Aware Email Replies

  • Intelligent Reply Preparation: Analyze the full context of an email thread before replying

  • Communication Pattern Analysis: Understand your communication history with the sender

  • Personalized Drafting: Create draft replies that match your communication style with specific contacts

  • Entity Recognition: Identify important dates, times, action items, and other entities in emails

  • Related Email Context: Consider other relevant emails when crafting replies

Calendar Integration

  • Event Creation: Create calendar events with natural language time descriptions

  • Event Detection: Automatically detect potential events mentioned in emails

  • Calendar Management: View, search, and manage your upcoming calendar events

  • Smart Scheduling: Schedule meetings with appropriate context from email conversations

Example Requests

You can ask Claude to use these capabilities with natural language requests like:

  • "Show me an overview of my inbox"

  • "Find all unread emails from my boss about the quarterly report"

  • "Help me reply to the last email from Sarah about the project deadline"

  • "Create a calendar event for the team meeting mentioned in John's email"

  • "What meetings do I have scheduled for next week?"

  • "Analyze this email thread and help me understand the key points before I reply"

  • "Draft a response to this email considering my previous communications with this person"

Available Resources

The MCP provides rich contextual resources that Claude can access:

  • Email Context: Detailed information about specific emails

  • Thread Context: Full conversation history for email threads

  • Sender Context: Information about your relationship and communication history with senders

  • Authentication Status: Current authentication state with Google

  • Gmail Status: Overview of your Gmail account

  • Server Information: Details about the MCP server configuration

Available Guides

The MCP includes several guides to help you get the most out of its capabilities:

  • Quick Start Guide: Basic instructions for getting started

  • Authentication Guide: Help with the authentication process

  • Search Guide: Advanced Gmail search syntax reference

  • Reply Guide: Best practices for context-aware email replies

  • Debug Guide: Troubleshooting common issues

☑️ This MCP is configured so Claude will always ask you for confirmation before doing any important action, such as sending an email or creating a meeting.

⚠ Beta Notice

This MCP is a WIP and is currently in beta.

📝 License

This project is licensed under the MIT License.

💡 Acknowledgements

  • This project uses the Model Context Protocol (MCP) developed by Anthropic

  • Gmail API access is provided by Google's API services

Available Tools

17 tools
authenticateA
    Start the complete OAuth authentication process.
    
    This tool opens a browser window and starts a local server to handle the callback.
    
    Returns:
        str: A message indicating that the authentication process has started.
    

Inputs: no named parameters.

check_auth_statusA
    Check the current authentication status.
    
    This tool provides a direct way to check if the user is authenticated
    without having to access the auth://status resource.
    
    Returns:
        Dict[str, Any]: The authentication status.
    

Inputs: no named parameters.

confirm_send_emailA
    Send a draft email after user confirmation.
    
    This tool sends a previously created draft email. It should ONLY be used
    after explicit user confirmation to send the email.
    
    Prerequisites:
    - The user must be authenticated
    - You need a draft_id from send_email_reply()
    - You MUST have explicit user confirmation to send the email
    
    Args:
        draft_id (str): The ID of the draft to send.
        
    Returns:
        Dict[str, Any]: The result of the operation, including:
            - success: Whether the operation was successful
            - message: A message describing the result
            - email_id: The ID of the sent email (if successful)
            
    Example usage:
    1. Create a draft: send_email_reply(email_id="...", reply_text="...")
    2. Ask for user confirmation: "Would you like me to send this email?"
    3. ONLY after user confirms: confirm_send_email(draft_id="...")
    
    IMPORTANT: Never call this function without explicit user confirmation.
    

Inputs: draft_id (required).

create_calendar_eventA
    Create a new event in the user's Google Calendar.
    
    This tool creates a new calendar event with the specified details.
    
    Prerequisites:
    - The user must be authenticated with Google Calendar access
    
    Args:
        summary (str): The title/summary of the event
        start_time (str): The start time of the event in ISO format (YYYY-MM-DDTHH:MM:SS) or simple date/time format ("5pm", "tomorrow 3pm")
        end_time (str, optional): The end time of the event. If not provided, you should ask the user for this information.
        description (str, optional): Description or notes for the event. If not provided, leave it blank.
        location (str, optional): Location of the event. If not provided, leave it blank.
        attendees (List[str], optional): List of email addresses of attendees. The current user will always be added automatically.
        color_name (str, optional): Color name for the event (e.g., "red", "blue", "green", "purple", "yellow", "orange")
        
    Returns:
        Dict[str, Any]: The result of the operation, including:
            - success: Whether the operation was successful
            - message: A message describing the result
            - event_id: The ID of the created event
            - event_link: Direct link to the event in Google Calendar
            - missing_info: List of missing information that should be asked from the user
            
    Example usage:
    1. Create a simple event:
       create_calendar_event(summary="Team Meeting", start_time="2023-12-01T14:00:00")
       
    2. Create a detailed event:
       create_calendar_event(
           summary="Project Kickoff",
           start_time="next monday at 10am",
           end_time="next monday at 11:30am",
           description="Initial meeting to discuss project scope",
           location="Conference Room A",
           attendees=["colleague@example.com", "manager@example.com"],
           color_id="2"
       )
    

Inputs: summary (required), start_time (required), end_time, description, +3 more.

detect_events_from_emailA
    Detect potential calendar events from an email.
    
    This tool analyzes an email to identify potential calendar events
    based on dates, times, and contextual clues.
    
    Prerequisites:
    - The user must be authenticated
    - You need an email ID from list_emails() or search_emails()
    
    Args:
        email_id (str): The ID of the email to analyze for events
        
    Returns:
        Dict[str, Any]: The detected events including:
            - success: Whether the operation was successful
            - events: List of potential events with details
            - email_link: Link to the original email
            
    Example usage:
    1. Get an email: email = get_email(email_id="...")
    2. Detect events: events = detect_events_from_email(email_id="...")
    3. Ask the user if they want to add the events to their calendar
    4. Ask the user for any missing information (end time, location, description, attendees)
    5. If confirmed, create the events using create_calendar_event()
    
    Important:
    - Always ask for user confirmation before creating calendar events
    - Always ask for missing information like end time, location, description, and attendees
    - Never use default values without user input
    - Always include the event_link when discussing events with the user
    

Inputs: email_id (required).

get_emailA
    Get a specific email by ID.
    
    This tool retrieves the full details of a specific email, including
    the body content, headers, and other metadata.
    
    Prerequisites:
    - The user must be authenticated. Check auth://status resource first.
    - You need an email ID, which can be obtained from list_emails() or search_emails()
    
    Args:
        email_id (str): The ID of the email to retrieve. This ID comes from the
                        list_emails() or search_emails() results.
        
    Returns:
        Dict[str, Any]: The email details including:
            - id: Email ID
            - thread_id: Thread ID
            - subject: Email subject
            - from: Sender information
            - to: Recipient information
            - cc: CC recipients
            - date: Email date
            - body: Email body content
            - snippet: Short snippet of the email
            - labels: Email labels
            - email_link: Direct link to the email in Gmail web interface
            
    Example usage:
    1. First check authentication: access auth://status resource
    2. Get a list of emails: list_emails()
    3. Extract an email ID from the results
    4. Get the full email: get_email(email_id="...")
    5. Always include the email_link when discussing the email with the user
    

Inputs: email_id (required).

get_email_countA
    Get the count of emails in the user's inbox.
    
    This tool retrieves the total number of messages in the user's Gmail account
    and the number of messages in the inbox.
    
    Prerequisites:
    - The user must be authenticated. Check auth://status resource first.
    - If not authenticated, guide the user through the authentication process.
    
    Returns:
        Dict[str, Any]: The email count information including:
            - email: The user's email address
            - total_messages: Total number of messages in the account
            - inbox_messages: Number of messages in the inbox
            - next_page_token: Token for pagination (if applicable)
            
    Example usage:
    1. First check authentication: access auth://status resource
    2. If authenticated, call get_email_count()
    3. If not authenticated, guide user to authenticate first
    

Inputs: no named parameters.

get_email_overviewA
    Get a simple overview of the user's emails.
    
    This tool provides a quick summary of the user's Gmail account,
    including counts and recent emails, all in one call.
    
    Returns:
        Dict[str, Any]: The email overview including:
            - account: Account information
            - counts: Email counts by label
            - recent_emails: List of recent emails with links
            - unread_count: Number of unread emails
            
    Note: Always include the email_link when discussing specific emails with the user.
    

Inputs: no named parameters.

list_calendar_eventsA
    List events from the user's Google Calendar.
    
    This tool retrieves a list of upcoming events from the user's calendar.
    
    Prerequisites:
    - The user must be authenticated with Google Calendar access
    
    Args:
        max_results (int, optional): Maximum number of events to return. Defaults to 10.
        time_min (str, optional): Start time for the search in ISO format or natural language.
                                 Defaults to now.
        time_max (str, optional): End time for the search in ISO format or natural language.
                                 Defaults to unlimited.
        query (str, optional): Free text search terms to find events that match.
        
    Returns:
        Dict[str, Any]: The list of events including:
            - events: List of calendar events with details and links
            - next_page_token: Token for pagination (if applicable)
            
    Example usage:
    1. List upcoming events:
       list_calendar_events()
       
    2. List events for a specific time range:
       list_calendar_events(time_min="tomorrow", time_max="tomorrow at 11:59pm")
       
    3. Search for specific events:
       list_calendar_events(query="meeting")
       
    Important:
    - Always include the event_link when discussing specific events with the user
    - The event_link allows users to directly access their events in Google Calendar
    - When listing multiple events, include the event_link for each event
    

Inputs: max_results, time_min, time_max, query.

list_emailsA
    List emails from the user's mailbox.
    
    This tool retrieves a list of emails from the specified label in the user's
    Gmail account, with basic information about each email.
    
    Prerequisites:
    - The user must be authenticated. Check auth://status resource first.
    - If not authenticated, guide the user through the authentication process.
    
    Args:
        max_results (int, optional): Maximum number of emails to return. Defaults to 10.
        label (str, optional): The label to filter by. Defaults to "INBOX".
            Common labels: "INBOX", "SENT", "DRAFT", "TRASH", "SPAM", "STARRED"
        
    Returns:
        Dict[str, Any]: The list of emails including:
            - emails: List of email objects with basic information and links
            - next_page_token: Token for pagination (if applicable)
            
    Example usage:
    1. First check authentication: access auth://status resource
    2. If authenticated, call list_emails(max_results=5, label="INBOX")
    3. If not authenticated, guide user to authenticate first
    4. Always include the email_link when discussing specific emails with the user
    

Inputs: max_results, label.

login_toolA
    Initiate the OAuth2 flow by providing a link to the Google authorization page.
    
    Returns:
        str: The authorization URL to redirect to.
    

Inputs: no named parameters.

logoutA
    Log out by revoking the access token and clearing the stored credentials.
    
    Returns:
        str: A success or error message.
    

Inputs: no named parameters.

prepare_email_replyA
    Prepare a context-rich reply to an email.
    
    This tool gathers comprehensive context for replying to an email,
    including the original email, thread history, sender information,
    communication patterns, and related emails.
    
    Prerequisites:
    - The user must be authenticated. Check auth://status resource first.
    - You need an email ID, which can be obtained from list_emails() or search_emails()
    
    Args:
        email_id (str): The ID of the email to reply to.
        
    Returns:
        Dict[str, Any]: Comprehensive context for generating a reply, including:
            - original_email: The email being replied to
            - thread_context: Information about the thread
            - sender_context: Information about the sender
            - communication_patterns: Analysis of communication patterns
            - entities: Entities extracted from the email
            - related_emails: Related emails for context
            
    Example usage:
    1. First check authentication: access auth://status resource
    2. Get a list of emails: list_emails()
    3. Extract an email ID from the results
    4. Prepare a reply: prepare_email_reply(email_id="...")
    5. Use the returned context to craft a personalized reply
    

Inputs: email_id (required).

process_auth_code_toolB
    Process the OAuth2 authorization code and state.
    
    Args:
        code (str): The authorization code from Google.
        state (str): The state parameter from Google.
        
    Returns:
        str: A success or error message.
    

Inputs: code (required), state (required).

search_emailsA
    Search for emails using Gmail's search syntax.
    
    This tool searches for emails matching the specified query using
    Gmail's powerful search syntax.
    
    Prerequisites:
    - The user must be authenticated. Check auth://status resource first.
    - If not authenticated, guide the user through the authentication process.
    
    Args:
        query (str): The search query using Gmail's search syntax.
            Examples:
            - "from:example@gmail.com" - Emails from a specific sender
            - "to:example@gmail.com" - Emails to a specific recipient
            - "subject:meeting" - Emails with "meeting" in the subject
            - "has:attachment" - Emails with attachments
            - "is:unread" - Unread emails
            - "after:2023/01/01" - Emails after January 1, 2023
        max_results (int, optional): Maximum number of emails to return. Defaults to 10.
        
    Returns:
        Dict[str, Any]: The search results including:
            - query: The search query used
            - emails: List of email objects matching the query with links
            - next_page_token: Token for pagination (if applicable)
            
    Example usage:
    1. First check authentication: access auth://status resource
    2. If authenticated, search for emails: search_emails(query="from:example@gmail.com")
    3. If not authenticated, guide user to authenticate first
    4. Always include the email_link when discussing specific emails with the user
    

Inputs: query (required), max_results.

send_email_replyA
    Create a draft reply to an email.
    
    This tool creates a draft reply to the specified email with the provided text.
    The draft is saved but NOT sent automatically - user confirmation is required.
    
    Prerequisites:
    - The user must be authenticated. Check auth://status resource first.
    - You need an email ID, which can be obtained from list_emails() or search_emails()
    - You should use prepare_email_reply() first to get context for crafting a personalized reply
    
    Args:
        email_id (str): The ID of the email to reply to.
        reply_text (str): The text of the reply.
        include_original (bool, optional): Whether to include the original email in the reply. Defaults to True.
        
    Returns:
        Dict[str, Any]: The result of the operation, including:
            - success: Whether the operation was successful
            - message: A message describing the result
            - draft_id: The ID of the created draft
            - confirmation_required: Always True to indicate user confirmation is needed
            
    Example usage:
    1. First check authentication: access auth://status resource
    2. Get a list of emails: list_emails()
    3. Extract an email ID from the results
    4. Prepare a reply: prepare_email_reply(email_id="...")
    5. Create a draft reply: send_email_reply(email_id="...", reply_text="...")
    6. IMPORTANT: Always ask for user confirmation before sending
    7. After user confirms, use confirm_send_email(draft_id='" + draft["id"] + "')
    
    IMPORTANT: You must ALWAYS ask for user confirmation before sending any email.
    Never assume the email should be sent automatically.
    

Inputs: email_id (required), reply_text (required), include_original.

suggest_meeting_timesA
    Suggest available meeting times within a date range.
    
    This tool analyzes the user's calendar and suggests available time slots
    for scheduling meetings based on their existing calendar events.
    
    Prerequisites:
    - The user must be authenticated with Google Calendar access
    
    Args:
        start_date (str): The start date of the range to check (can be natural language like "tomorrow")
        end_date (str): The end date of the range to check (can be natural language like "next friday")
        duration_minutes (int, optional): The desired meeting duration in minutes. Defaults to 60.
        working_hours (str, optional): Working hours in format "9-17" (9am to 5pm). Defaults to 9am-5pm.
        
    Returns:
        Dict[str, Any]: The suggested meeting times including:
            - success: Whether the operation was successful
            - suggestions: List of suggested meeting times with formatted date/time
            - message: A message describing the result
            
    Example usage:
    1. Find meeting times for tomorrow:
       suggest_meeting_times(start_date="tomorrow", end_date="tomorrow")
       
    2. Find meeting times for next week with custom duration:
       suggest_meeting_times(
           start_date="next monday", 
           end_date="next friday", 
           duration_minutes=30
       )
       
    3. Find meeting times with custom working hours:
       suggest_meeting_times(
           start_date="tomorrow", 
           end_date="friday", 
           working_hours="10-16"
       )
       
    Important:
    - The tool respects the user's existing calendar events
    - Suggestions are limited to working hours (default 9am-5pm)
    - Weekends are excluded by default
    - The tool will return at most 10 suggestions
    

Inputs: start_date (required), end_date (required), duration_minutes, working_hours.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.9/5.0

    Scored across 17 tools

    Disambiguation4/5

    Most tools have distinct purposes, but there is some overlap between list_emails and search_emails, as both retrieve emails with similar outputs, which could cause confusion. Additionally, authenticate and login_tool both handle authentication initiation, though their descriptions clarify different aspects of the process. Overall, the set is mostly clear with minor ambiguities.

    Naming Consistency4/5

    The naming follows a consistent snake_case pattern throughout, with clear verb_noun structures (e.g., get_email, list_emails, create_calendar_event). However, there are minor deviations like authenticate and login_tool, which are less descriptive compared to others, and check_auth_status uses a verb_adjective_noun pattern, slightly breaking consistency.

    Tool Count4/5

    With 17 tools, the count is slightly high but reasonable for a Gmail and Calendar integration, covering authentication, email management, and calendar operations. It avoids being excessive, though some tools like authenticate and login_tool could potentially be consolidated to streamline the set.

    Completeness5/5

    The tool set provides comprehensive coverage for Gmail and Calendar operations, including authentication, email listing/searching/replying, calendar event creation/listing, and integration features like detecting events from emails. There are no obvious gaps; it supports full workflows from access to action, including user confirmation steps for sensitive operations.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables AI assistants to interact with Gmail accounts for reading unread emails, creating draft replies with proper threading, and managing messages, with optional professional writing guidelines, templates, and Google Docs/Calendar integration.
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI assistants to manage Gmail through natural language interactions, including sending, reading, searching emails, and managing labels with auto authentication support.
      1
      MIT