Google Docs & Gmail MCP Server

Google Docs & Gmail MCP Server

A Model Context Protocol-style server using FastAPI that integrates Google Docs and Gmail via official Google APIs with OAuth 2.0 and interactive terminal-based human-in-the-loop approval.

Category
访问服务器

README

Google Docs & Gmail MCP Server

A complete Model Context Protocol (MCP)-style server in Python using FastAPI that integrates directly with Google Docs and Gmail via the official Google APIs with OAuth 2.0 authentication and interactive terminal-based human-in-the-loop approval.


📁 Project Structure

google-mcp-server/
├── server.py          → FastAPI app with tool endpoints & terminal confirmation
├── auth.py            → Google OAuth 2.0 authentication & token persistence
├── docs_tool.py       → Google Docs tool (appends content to docs)
├── gmail_tool.py      → Gmail tool (creates email drafts)
├── requirements.txt   → Python package dependencies
├── .gitignore         → Prevents committing credentials.json & token.json
├── Procfile           → Railway / PaaS process declaration
├── railway.toml       → Railway build & healthcheck configuration
├── Dockerfile         → Container definition for cloud deployments
├── deployment.md      → Detailed Railway cloud deployment guide
├── README.md          → Setup, configuration, and usage instructions
├── credentials.json   → (NOT committed — downloaded from Google Cloud Console)
└── token.json         → (NOT committed — auto-generated after first OAuth login)

⚙️ Features

  1. Google OAuth 2.0 Authentication (auth.py):

    • Scopes configured:
      • https://www.googleapis.com/auth/documents (Google Docs read/write)
      • https://www.googleapis.com/auth/gmail.compose (Gmail draft creation)
    • Automatically loads existing token.json without re-opening the browser.
    • Automatically refreshes expired tokens.
    • Automatically launches browser-based OAuth consent flow on initial run and writes token.json.
  2. Google Docs Tool (docs_tool.py):

    • append_to_doc(doc_id: str, content: str)
    • Appends text content to the end of any Google Doc using the official Google Docs API v1 (documents.batchUpdate).
  3. Gmail Tool (gmail_tool.py):

    • create_email_draft(to: str, subject: str, body: str)
    • Creates a new draft message in the authenticated user's Gmail using the official Gmail API v1 (users.drafts.create).
  4. FastAPI Server with Human-in-the-loop Approval (server.py):

    • POST /append_to_doc: Appends text to a document.
    • POST /create_email_draft: Creates an email draft.
    • Terminal Gatekeeper: Before executing any tool action, the server outputs the action name and exact payload to the console and asks:
      ============================================================
      ⚠️  [ACTION PENDING APPROVAL]: append_to_doc
      ------------------------------------------------------------
      Payload:
      {
        "doc_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
        "content": "New analysis findings..."
      }
      ============================================================
      Approve? (y/n): 
      
      • Typing y (or Y) approves and executes the action.
      • Typing n (or any other input) rejects the action and returns 403 Forbidden with a rejection notification to the caller.

🚀 Setup & Installation

1. Prerequisites


2. Google Cloud Setup & Credentials

  1. Go to the Google Cloud Console.
  2. Create a new project (e.g., google-mcp-server).
  3. Enable the required APIs:
    • Search for Google Docs API and click Enable.
    • Search for Gmail API and click Enable.
  4. Configure the OAuth Consent Screen:
    • Go to APIs & Services > OAuth consent screen.
    • Select External (or Internal for Google Workspace) and click Create.
    • Enter an App name (e.g., Google MCP Server) and your support email.
    • In Scopes, add:
      • .../auth/documents
      • .../auth/gmail.compose
    • In Test users, add your own Google email address (if external/testing mode).
    • Save and continue.
  5. Create OAuth 2.0 Credentials:
    • Go to APIs & Services > Credentials.
    • Click + CREATE CREDENTIALS > OAuth client ID.
    • Application type: Desktop app.
    • Name: MCP Desktop Client.
    • Click Create.
    • Click DOWNLOAD JSON and rename the downloaded file to credentials.json.
    • Place credentials.json in the root directory of this repository (c:\MCP-SERVER\credentials.json).

3. Install Dependencies

Create a virtual environment (recommended) and install dependencies:

# Optional: create virtual environment
python -m venv venv

# Windows activate:
venv\Scripts\activate

# Linux/macOS activate:
source venv/bin/activate

# Install requirements
pip install -r requirements.txt

💻 Running the Server

Start the server using python or uvicorn:

python server.py

Or:

uvicorn server:app --host 127.0.0.1 --port 8000 --reload

Once running:

  • API Base URL: http://127.0.0.1:8000
  • Interactive Swagger UI Docs: http://127.0.0.1:8000/docs
  • ReDoc Documentation: http://127.0.0.1:8000/redoc

Note on First Run: The first time you make a request (or run python auth.py), a browser window will automatically open asking you to log into Google and grant permissions. Once granted, a token.json file is saved locally so all subsequent requests run without browser interaction.


📡 API Usage & Endpoints

1. Root & Health Check

GET /

Returns server status and registry of available MCP tools.

curl -X GET http://127.0.0.1:8000/

Response:

{
  "server": "Google Docs & Gmail MCP Server",
  "version": "1.0.0",
  "status": "online",
  "tools": [
    {
      "name": "append_to_doc",
      "endpoint": "/append_to_doc",
      "method": "POST",
      "description": "Appends text content to an existing Google Document.",
      "required_parameters": ["doc_id", "content"]
    },
    {
      "name": "create_email_draft",
      "endpoint": "/create_email_draft",
      "method": "POST",
      "description": "Creates a draft email in Gmail.",
      "required_parameters": ["to", "subject", "body"]
    }
  ]
}

2. Append Content to Google Doc

POST /append_to_doc

Request Body:

{
  "doc_id": "YOUR_GOOGLE_DOC_ID",
  "content": "\n## Summary\nHere is the newly appended text.\n"
}

cURL Example:

curl -X POST http://127.0.0.1:8000/append_to_doc \
  -H "Content-Type: application/json" \
  -d '{
    "doc_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
    "content": "\n\n### Appended Section\nAutomated analysis report generated."
  }'

Terminal Prompt:

============================================================
⚠️  [ACTION PENDING APPROVAL]: append_to_doc
------------------------------------------------------------
Payload:
{
  "doc_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
  "content": "\n\n### Appended Section\nAutomated analysis report generated."
}
============================================================
Approve? (y/n): y
✅ Action APPROVED. Executing...

Success Response (HTTP 200):

{
  "status": "success",
  "message": "Successfully appended 64 characters to document 'Product Review Summary'.",
  "data": {
    "status": "success",
    "document_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
    "document_title": "Product Review Summary",
    "characters_appended": 64
  }
}

Rejection Response (HTTP 403):

{
  "detail": {
    "status": "rejected",
    "message": "Action 'append_to_doc' was not approved by the operator in terminal.",
    "payload": {
      "doc_id": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms",
      "content": "..."
    }
  }
}

3. Create Gmail Draft

POST /create_email_draft

Request Body:

{
  "to": "recipient@example.com",
  "subject": "Weekly Report Draft",
  "body": "Hi Team,\n\nPlease review the draft attached.\n\nBest,\nSai"
}

cURL Example:

curl -X POST http://127.0.0.1:8000/create_email_draft \
  -H "Content-Type: application/json" \
  -d '{
    "to": "team@example.com",
    "subject": "Weekly Review Draft",
    "body": "Hello,\n\nPlease find the review draft in your mailbox."
  }'

Terminal Prompt:

============================================================
⚠️  [ACTION PENDING APPROVAL]: create_email_draft
------------------------------------------------------------
Payload:
{
  "to": "team@example.com",
  "subject": "Weekly Review Draft",
  "body": "Hello,\n\nPlease find the review draft in your mailbox."
}
============================================================
Approve? (y/n): y
✅ Action APPROVED. Executing...

Success Response (HTTP 200):

{
  "status": "success",
  "message": "Successfully created Gmail draft (ID: r-1234567890) for 'team@example.com'.",
  "data": {
    "status": "success",
    "draft_id": "r-1234567890",
    "message_id": "18d1a2b3c4d5e6f7",
    "to": "team@example.com",
    "subject": "Weekly Review Draft"
  }
}

🧪 Testing Suite

You can run automated unit tests that verify all endpoints, authentication handling, Google Docs appending, and Gmail draft generation using mock Google API services:

pytest -v

🔒 Security Best Practices

  • credentials.json contains your client secret and token.json contains refresh tokens granting access to your Docs and Gmail.
  • Both files are ignored in .gitignore — never commit them to public version control.
  • The interactive terminal approval mechanism acts as a guardrail against unauthorized or unintended agent actions.

☁️ Cloud Deployment (Railway)

To deploy this MCP server to Railway as a 24/7 cloud API service:

  • Complete step-by-step instructions, environment variable setup (GOOGLE_TOKEN_JSON, GOOGLE_CREDENTIALS_JSON, REQUIRE_TERMINAL_APPROVAL=false), and security options are detailed in deployment.md.

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选