Skip to content

coderkrp/gmail-agent-gateway

Repository files navigation

Gmail API Gateway for Agent Tools

Securely bridge AI agents to Gmail without handing them the keys.

CI Build Status Python Version License Release Version

Gmail Agent Gateway is a secure local API gateway that lets AI agents interact with Gmail through fine-grained, sanitized tools — not direct mailbox access. It handles OAuth 2.0, rate limiting, and operational metrics so you can focus on building the integration scripts your agent actually needs.

Table of Contents


Why This Project?

Integrating AI agents with email poses significant security and engineering challenges:

  1. Excessive Privilege: Giving an agent raw API credentials or direct access to a full mailbox endpoint creates a high risk of accidental data deletion or unauthorized email transmission.
  2. Context Bloat & Fragility: Agents should not be parsing nested MIME structures, stripping complex HTML, or handling OAuth handshakes inside their prompt loops.
  3. Auditability: It is difficult to track, log, and rate-limit email reads, writes, and deletions when they are performed directly by autonomous agent code.

This gateway separates these concerns by exposing secure local REST endpoints that developers consume to build focused, task-specific agent tools.


Quick Start

1. Install

pip install -e .

2. Configure

cp .env.example .env
# Edit .env and configure at least API_KEY, OAUTH_REDIRECT_URI, and OAUTH_CLIENT_SECRETS_FILE

3. Run

mailserver-run

Open https://127.0.0.1:5000/ or https://127.0.0.1:5000/oauth2callback in your browser to authorize Gmail access.

4. Verify

curl -k -H "X-API-Key: <your-api-key>" \
  "https://127.0.0.1:5000/api/messages?label_ids=INBOX&max_results=1"

Note

Detailed installation, Google Cloud Console OAuth credential creation, and remote VPS/Cloud deployment instructions are available in the Setup and Deployment Guide.


Security Model

  • API Key Authentication: Required on all /api/* endpoints via the X-API-Key header.
  • Administrative Isolation: Permanent deletions require a separate X-Admin-Key header.
  • Gmail OAuth 2.0: Mailbox access uses Google OAuth 2.0. Credentials remain local and are never shared.
  • Rate Limiting: Built-in in-memory rate limiting enforces mutation control.
  • Safe-by-Default Deletions: Standard delete operations move messages to the trash rather than deleting them permanently.

For a full breakdown of the threat model, design mitigations, and production security recommendations, see docs/SECURITY.md and the root SECURITY.md.


Usage Examples

List Inbox Messages

curl -k -H "X-API-Key: <your-api-key>" \
  "https://127.0.0.1:5000/api/messages?label_ids=INBOX&max_results=2"

Response:

{
  "success": true,
  "messages": [
    {
      "id": "18f4abc123",
      "threadId": "18f4abc123",
      "snippet": "Build finished successfully...",
      "subject": "CI result",
      "from": "ci@example.com"
    }
  ],
  "nextPageToken": "1234567890"
}

Send an Email

curl -k -X POST "https://127.0.0.1:5000/api/send" \
  -H "X-API-Key: <your-api-key>" \
  -H "Content-Type: application/json" \
  -d '{"to":"recipient@example.com","subject":"Hello","body":"Test"}'

Response:

{
  "success": true,
  "message": {
    "id": "18f4abc123",
    "threadId": "18f4abc123",
    "labelIds": ["SENT"]
  }
}

Configuration

Server settings (e.g. ports, API keys, rate limits, and CORS origins) are loaded from environment variables or a .env file.

See the Configuration Reference for the complete list of settings, defaults, and descriptions.


API Endpoints

The gateway provides REST endpoints for listing, reading, sending, and labeling emails, alongside operational metrics and token revocation.

See docs/API.md for the detailed API reference, request/response schemas, and example queries.


Example Integration Scripts

The repository includes ready-to-use example scripts in the examples/ directory:

  1. fetch_and_sanitize_unread.py: Retrieves unread emails, strips HTML/scripts, collapses whitespace, redacts secrets/PII, and outputs clean Markdown optimal for LLM prompts.
  2. attach_labels.py: Applies labels to emails after validating that the requested labels actually exist in the user's mailbox.

Architecture

flowchart TD
    Agent["AI Agent (LLM)"] -->|Runs custom tool| Script["Custom Tools & Scripts\n(e.g., fetch_and_sanitize_unread.py)"]
    Script -->|Authenticated via X-API-Key| Flask["Flask API Gateway"]
    Browser["Local browser"] --> OAuthRoute["/oauth2callback"]
    OAuthRoute --> GoogleOAuth["Google OAuth 2.0"]
    GoogleOAuth --> OAuthRoute
    Flask --> Auth["API Key & OAuth validation"]
    Auth --> GmailService["GmailService"]
    GmailService --> GmailAPI["Gmail API"]
    Auth --> Metrics["SQLite metrics"]
    OAuthRoute --> TokenFile["token_cache.json"]
Loading

The Flask layer owns routing, rate limiting, and caller authentication. Custom scripts consume these endpoints to build the actual tools exposed to the agent.

See docs/ARCHITECTURE.md for detailed sequence diagrams, request flows, and component responsibilities.


Contributing

Contributions are welcome! Please read CONTRIBUTING.md for development setup instructions, code style expectations, and the tag-based release process.


Changelog

See CHANGELOG.md for release notes and changes between versions.


License

This project is licensed under the MIT License. See LICENSE for details.


Author

Built by Coderkrp. Found a bug? Open an issue. Have a question? Reach out on GitHub.


Related Projects

About

Securely bridge AI agents to Gmail without handing them the keys.

Resources

License

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors