logo
Free, unlimited AI code reviews that run on commit
git-lrc git-lrc GitHub Install Now We'd appreciate a star git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt

auto-authenticated-gmail-interface

A robust Model Context Protocol (MCP) server providing programmatic control over the Gmail ecosystem via natural language directives. Facilitates secure, automated email composition, retrieval, archival, and detailed label administration, featuring integrated, hands-free OAuth2 credential handling.

Author

auto-authenticated-gmail-interface logo

raghavared

MIT License

Quick Info

GitHub GitHub Stars 0
NPM Weekly Downloads 7879
Tools 1
Last Updated 2026-02-19

Tags

gmailmcptoolsgmail mcpmanage gmailraghavared gmail

Automated Gmail Management System via MCP

This repository details an MCP server implementation designed to bridge Claude Desktop with the Gmail API, featuring seamless, automatic OAuth2 authentication setup. It empowers AI agents to perform complex electronic mail operations using plain language instructions.

smithery badge

Core Capabilities

  • Transmission: Dispatch new electronic mail items, specifying recipients, subjects, body text, and file attachments.
  • Encoding Fidelity: Full Unicode support for both headers and message bodies, ensuring accurate representation of international scripts.
  • Content Retrieval: Fetch individual message content via unique identifiers, with sophisticated parsing of complex MIME structures.
  • Metadata Inspection: View details pertaining to attached resources (names, content types, file sizes).
  • Filtering & Querying: Execute granular searches across the mailbox using established Gmail search operators (sender, date parameters, content matching).
  • Label Hierarchies: Complete toolkit for manipulating labels, allowing for the creation, modification, listing, and removal of both system and custom classification tags.
  • Inventory Listing: Obtain lists of messages residing in the Inbox, Sent folder, or any custom tag location.
  • Status Toggling: Mark messages as read or unread.
  • Relocation: Reassign messages between different organizational tags/folders.
  • Purging: Permanently eliminate mail items.
  • Bulk Processing: Execute high-throughput batch modifications across multiple messages concurrently for streamlined inbox hygiene.
  • API Compliance: Full adherence to the underlying Gmail REST API specifications.
  • Authentication Ease: Simplified OAuth2 handshake process that automatically launches the necessary browser window for initial authorization.
  • Credential Persistence: Supports both desktop client and web application credential storage mechanisms, with globally accessible credential retention.

Deployment and Authorization Procedures

Installation via Smithery Utility

For expedited setup within the Claude Desktop environment using Smithery:

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

Manual Setup

  1. Google Cloud Project Configuration:

    a. Establish a Google Cloud Project: - Navigate to the Google Cloud Console. - Initiate a new project or select an existing one. - Activate the Gmail API service within the project settings.

    b. Generate OAuth 2.0 Credentials: - Access "APIs & Services" -> "Credentials". - Select "Create Credentials" -> "OAuth client ID". - Designate the application type ("Desktop app" or "Web application"). - Name the credential set and generate the keys. - Crucially, for Web applications, register http://localhost:3000/v2/auth/google/callback as an authorized redirect URI. - Export and save the resulting JSON file containing your client secrets. - Rename this file to token.json.

  2. Initiating Authorization Sequence:

You have two options for running the auth command:

a. Global Credential Storage (Recommended):
bash
# Create the secure storage directory if it doesn't exist
mkdir -p ~/.gmail-mcp
# Move your secrets file to the designated global path
mv token.json ~/.gmail-mcp/

# Execute authorization from any directory
npx @raghavared/gmail-mcp auth


b. Local Directory Authorization:
bash
# Keep token.json in your current working directory
# The utility will automatically copy it to the global location
npx @raghavared/gmail-mcp auth

The authorization routine performs the following actions: - Locates token.json either locally or within ~/.gmail-mcp/. - Duplicates the file to the global configuration folder if sourced locally. - Triggers the default browser to initiate the Google sign-in and consent process. - Persists the final, valid access tokens into ~/.gmail-mcp/credentials.json.

> **Configuration Notes**:
> - Successful authorization results in credentials being stored persistently in `~/.gmail-mcp/` for future use across sessions.
> - Both common OAuth flows (installed and web) are supported.
> - If utilizing web client secrets, ensure the specified callback URL is precisely configured in the Google Cloud Console.
  1. Integration Configuration in Claude Desktop:

{ "mcpServers": { "gmail": { "command": "npx", "args": [ "@raghavared/gmail-mcp" ] } } }

Docker Deployment Strategy

If containerization is preferred:

  1. Authentication within Docker: bash docker run -i --rm \ --mount type=bind,source=/path/to/token.json,target=/token.json \ -v gmail-mcp:/gmail-server \ -e GMAIL_OAUTH_PATH=/token.json \ -e "GMAIL_CREDENTIALS_PATH=/gmail-server/credentials.json" \ -p 3000:3000 \ mcp/gmail auth

  2. Runtime Configuration for Docker Usage:

{ "mcpServers": { "gmail": { "command": "docker", "args": [ "run", "-i", "--rm", "-v", "mcp-gmail:/gmail-server", "-e", "GMAIL_CREDENTIALS_PATH=/gmail-server/credentials.json", "gmail-mcp" ] } } }

Server Deployment in Cloud/Proxy Environments

For operational contexts such as n8n or other remote execution platforms, a custom callback URI must be specified during authorization setup:

bash npx @raghavared/gmail-mcp auth {domain}/v2/auth/google/callback

Cloud Environment Prerequisites

  1. Reverse Proxy Setup:

    • Configure your execution container (e.g., n8n) to expose the authentication port.
    • Establish a reverse proxy layer to route external traffic from your designated domain (e.g., domain.com) to that internal port.
  2. DNS Resolution:

    • Update your domain's DNS records (A record) to point to your cloud server's public IP address.
  3. GCP Credential Update:

    • In the Google Cloud Console, update the authorized redirect URIs to include your public-facing endpoint (e.g., https://domain.com/v2/auth/google/callback).
  4. Execute Authorization with Custom URI: bash npx @raghavared/gmail-mcp auth https://domain.com/v2/auth/google/callback

  5. Application Configuration:

    { "mcpServers": { "gmail": { "command": "npx", "args": [ "@raghavared/gmail-mcp" ] } } }

This advanced configuration ensures that the necessary OAuth redirection handshake functions correctly when the server is not directly accessible via localhost (e.g., in containerized or cloud setups).

Exposed Interface Functions

This server exposes the following actionable tools available to the AI assistant:

1. Transmit Message (send_email)

Sends a new electronic mail item immediately.

{ "to": ["target@domain.net"], "subject": "Urgent Follow-Up", "body": "Please review the attached documentation prior to our discussion.\n\nThank you,", "cc": ["secondary@domain.net"], "bcc": ["private@domain.net"] }

2. Stash Message as Draft (draft_email)

Creates a message artifact without immediate dispatch.

{ "to": ["reviewer@domain.org"], "subject": "Initial Project Outline Draft", "body": "This is the preliminary outline for Q3 initiatives.", "cc": ["supervisor@domain.org"] }

3. Retrieve Specific Message (read_email)

Fetches the complete content structure for a designated email ID.

{ "messageId": "a1b2c3d4e5f6g7h8" }

4. Mail Index Search (search_emails)

Queries the mailbox content using standard Gmail search logic.

{ "query": "label:PROMOTION_UPDATES older_than:30d is:read", "maxResults": 5 }

5. Tweak Message Tags (modify_email)

Applies or revokes classification tags on a message (equivalent to moving or archiving).

{ "messageId": "a1b2c3d4e5f6g7h8", "addLabelIds": ["STARRED"], "removeLabelIds": ["INBOX", "UNREAD"] }

6. Archive Message Permanently (delete_email)

Removes a message from view and trash its contents.

{ "messageId": "a1b2c3d4e5f6g7h8" }

7. Enumerate Available Tags (list_email_labels)

Returns a complete roster of all active Gmail classification tags.

{}

8. Establish New Tag (create_label)

Generates a novel classification tag within the user's account.

{ "name": "Client_FY25_Assets", "messageListVisibility": "show", "labelListVisibility": "labelShow" }

9. Recalibrate Existing Tag (update_label)

Modifies the descriptive name or display properties of a pre-existing tag.

{ "id": "Label_XYZ987654321", "name": "Critical_FY25_Assets", "messageListVisibility": "show", "labelListVisibility": "labelShow" }

10. Erase Tag (delete_label)

Decommissions a user-defined classification tag.

{ "id": "Label_XYZ987654321" }

11. Lookup or Instantiate Tag (get_or_create_label)

Checks for a tag by name; if absent, it is provisioned immediately.

{ "name": "FollowUp_Pending", "messageListVisibility": "show", "labelListVisibility": "labelShowIfUnread" }

12. Mass Tag Adjustment (batch_modify_emails)

Applies or removes tags across a collection of message identifiers efficiently.

{ "messageIds": ["id1", "id2", "id3", "id4"], "addLabelIds": ["INBOX"], "removeLabelIds": ["TRASH"], "batchSize": 25 }

13. Mass Deletion (batch_delete_emails)

Performs sequential, high-volume permanent removal of selected messages.

{ "messageIds": ["id1", "id2", "id3", "id4"], "batchSize": 25 }

Advanced Search Syntax Reference

The search_emails function natively interprets Gmail's robust query operators:

Operator Sample Query Description
from: from:ceo@corp.com Filters messages originating from a specific address.
to: to:team@internal.org Filters messages explicitly addressed to this recipient.
subject: subject:"Quarterly Review" Matches text contained within the message subject line.
has:attachment has:attachment Isolates messages containing associated files.
after: after:2024-05-15 Retrieves mail received subsequent to the specified date.
before: before:2024-05-01 Retrieves mail received prior to the specified date.
is: is:snoozed Filters based on message status flags.
label: label:Important Focuses results based on a specific classification tag.

You may concatenate multiple operators: from:support@service.net before:2024-01-01 is:unread

Technical Deep Dive

Content Parsing Engine

The server is engineered to intelligently reconstruct email content from complex message envelopes:

  • Prioritizes the extraction of the human-readable plain text payload.
  • If plain text is absent, it safely resorts to parsing the HTML representation.
  • Seamlessly navigates and processes nested multi-part MIME entities.
  • Provides structured metadata for all embedded attachments (file metadata).
  • Maintains fidelity of essential headers (sender, recipient list, subject, timestamp).

Internationalization Support

The system is fully compliant with standards for handling non-ASCII character sets across all textual fields, including: - Asian languages (CJK) and other complex scripts. - Special symbols and Unicode characters. - Ensures correct character set encoding for cross-client compatibility.

Comprehensive Tag Administration

Tooling for tag management offers complete lifecycle control:

  • Provisioning: Create new classification tags, setting default viewing behaviors.
  • Modification: Rename tags or alter their display rules.
  • Retirement: Delete user-created tags (system tags are protected from removal).
  • Idempotent Retrieval: Fetch a tag identifier by its name, or provision it if missing.
  • Inventory: Obtain a complete listing of all tags.
  • Visibility Control: Fine-grained control over display:
    • messageListVisibility: Dictates appearance next to the message list (show or hide).
    • labelListVisibility: Controls listing behavior (labelShow, labelShowIfUnread, or labelHide).

These granular control features permit sophisticated automated email organization directly via the AI agent.

Efficiency Through Batching

The server incorporates high-efficiency pipelines for volume operations:

  • Designed to handle up to 50 distinct operations per API call (adjustable via batchSize).
  • Automatically fragments extensive requests into smaller, API-compliant segments.
  • Provides granular reporting on the success or failure status of each item within the batch.
  • Includes built-in retry logic for transient errors, optimizing throughput for bulk inbox cleansing tasks.

Security Posture

  • OAuth access tokens are encrypted and stored locally within the user's designated directory (~/.gmail-mcp/).
  • Utilizes secure, persistent refresh tokens for offline access continuity.
  • Warning: Never expose or commit token.json or credentials.json files to public repositories.
  • Periodically audit and revoke tokens for unused client applications via your Google Security settings.
  • Access to stored credentials is strictly scoped to the local user profile.

Common Diagnostics

  1. Authentication File Missing/Inaccessible

    • Verify token.json placement in either the execution path or ~/.gmail-mcp/.
    • Confirm appropriate file read/write permissions.
  2. Credential Structure Error

    • Ensure the source JSON uses standard Google OAuth formats (web or installed).
    • For web credentials, confirm the registered redirect URI matches exactly.
  3. Port 3000 Conflict

    • The authorization process requires port 3000. Terminate any existing process utilizing this port before re-running authentication.
  4. Batch Processing Errors

    • Failures in batch routines trigger individual item retries.
    • Examine detailed logs for specific API throttling or access denial messages.
    • If rate limiting persists, decrease the batchSize parameter.

Development and Licensing

We welcome external contributions; please submit a Pull Request for review.

License: MIT

Support: For bugs or inquiries, please open an issue on the project's source code repository.

== Contextual Definition: Business Management Utilities == Business management utilities encompass the spectrum of applications, computational frameworks, governance mechanisms, analytical solutions, and operational philosophies employed by entities to successfully navigate shifting market dynamics, maintain competitive advantage, and enhance overall organizational productivity.

These tools often span departmental silos, addressing needs related to foresight (planning), execution efficiency (process), record-keeping, human capital administration, critical assessment (decision support), and performance monitoring (control).

The swift evolution of technology in the last decade has led to an overwhelming proliferation of available business software, making judicious selection and tailored implementation paramount. Managers must adopt a strategic posture, adapting tools to fit established organizational requirements rather than conforming organizational processes rigidly to vendor defaults. Successful integration hinges on effective implementation and precise alignment of the chosen technology with business imperatives.

== Prevalent Management Instruments (Circa 2013 Survey Data) == Historical data suggests high adoption rates for strategic and structural tools, including:

  • Strategic Planning Frameworks
  • Client Relationship Management (CRM) Systems
  • Employee Feedback and Survey Mechanisms
  • Competitive Benchmarking Procedures
  • Balanced Scorecard Implementation
  • Core Competency Identification
  • Operational Outsourcing Strategies
  • Structured Change Management Programs
  • Supply Chain Optimization Platforms
  • Mission and Vision Statement Documentation
  • Market Segmentation Analysis
  • Total Quality Management (TQM) Methodologies

== Enterprise Software Applications == Business software refers to collections of programs utilized by personnel to execute core organizational functions. These applications are designed to elevate output metrics, provide precise operational measurement, and automate routine tasks. The landscape has progressed from rudimentary Management Information Systems (MIS) through expansive Enterprise Resource Planning (ERP) suites, incorporating CRM capabilities, and now largely resides in the cloud-based management service domain.

While IT investment correlates with organizational gains, maximizing value depends critically on two factors: the efficacy of the system's deployment and the deliberate process of selecting and customizing the appropriate software tools.

== Tools Tailored for Small to Medium Enterprises (SMEs) == SME-focused utilities are vital as they frequently provide cost-effective mechanisms to conserve...

See Also

`