TG

taylorwilsdon/google_workspace_mcp

Deployment & DevOps
2,8 тыс. stars 0 forks Качество 68 Тренд 68

Control Gmail, Google Calendar, Docs, Sheets, Slides, Chat, Forms, Tasks, Search & Drive with AI - Comprehensive Google Workspace MCP Server & CLI Tool

Обзор

Full natural language control over Google Calendar, Drive, Gmail, Docs, Sheets, Slides, Forms, Tasks, Contacts, and Chat through all MCP clients, AI assistants and developer tools. Includes a full featured CLI & Code Mode for use with tools like Claude Code and Codex! , it can do things that Google's own tooling and the built in integrations with Claude and ChatGPT can't even dream of. With Remote OAuth2.1 multi-user support, fine-grained editing tools and the most extensive coverage of any Google Workspace tool in existance, Workspace MCP is in a different class. Offering native OAuth 2.1, stateless mode and external auth server support, it's also the only Workspace MCP you can host for your whole organization centrally & securely! ⚡ Start Quick Start · Prerequisites Google Cloud · Credentials 🧰 Tools All Tools · Tool Tiers CLI · Start Server 🔌 Connect Quick Start · Claude Desktop Claude Code · VS Code · LM Studio 🚀 Deploy OAuth 2.

README


See it in action:


Overview

Workspace MCP is the single most complete MCP server, the only that integrates all major Google Workspace services with AI assistants and all agent platforms. The entire toolset is available for CLI usage supporting both local and remote instances.

Features

12 services  —  Gmail · Drive · Calendar · Docs · Sheets · Slides · Forms · Chat · Apps Script · Tasks · Contacts · Search


Security & Compliance


Quick Start

Set credentials → pick a launch command → connect your client

Credential setup → · All launch options → · Tier details →


Quick Start — Connect Claude to Google Workspace

The recommended setup is to run an instance and connect Claude to it via a Connector. Full instructions at workspacemcp.com/quick-start.


Prerequisites

Python 3.10+ · uv/uvx · Google Cloud Project with OAuth 2.0 credentials

If you want the GCS credential store backend, install the optional dependency first:

uv sync --extra gcs
# or
pip install "workspace-mcp[gcs]"

Configuration

Google Custom Search Setup

Start the Server

📌 Transport Mode Guidance: Use streamable HTTP mode (--transport streamable-http) for all modern MCP clients including Claude Code, VS Code MCP, and MCP Inspector. For Claude Desktop, run an instance and connect via a Connector. Stdio mode is a legacy fallback. For deployments, prefer OAuth 2.1 with stateless mode (MCP_ENABLE_OAUTH21=true, WORKSPACE_MCP_STATELESS_MODE=true) unless you need local attachment or credential storage.

OAuth state safety: Legacy stdio starts a local-only OAuth callback server. In single-user mode only, it may recover a missing Google state parameter by consuming the most recent pending local OAuth state. This fallback is intentionally disabled outside single-user mode because it can cross session boundaries. Do not enable or emulate this behavior in streamable HTTP, hosted, or multi-user deployments; those modes must require an explicit state match.

CLI

The workspace-cli command lists tools and calls them against a running server — with encrypted, disk-backed OAuth token caching so you only authenticate once. On first run it opens a browser for Google consent; subsequent runs reuse the cached tokens automatically.

Tokens are stored encrypted at ~/.workspace-mcp/cli-tokens/ using a Fernet key auto-generated at ~/.workspace-mcp/.cli-encryption-key.

To use workspace-cli globally, you’ll want to start in this repo and run uv tool install .

Once complete, you’ll have workspace-cli available globally via workspace-cli

Note: there is a public (but abandoned) pypi package with the same name - do not use uvx, as it will pull the wrong thing.

Tool Tiers

The server organizes tools into three progressive tiers for simplified deployment. Choose a tier that matches your usage needs and API quota requirements.

Usage Examples

# Basic tier selection
uv run main.py --tool-tier core                            # Start with essential tools only
uv run main.py --tool-tier extended                        # Expand to include management features
uv run main.py --tool-tier complete                        # Enable all available functionality

# Selective service loading with tiers
uv run main.py --tools gmail drive --tool-tier core        # Core tools for specific services
uv run main.py --tools gmail --tool-tier extended          # Extended Gmail functionality only
uv run main.py --tools docs sheets --tool-tier complete    # Full access to Docs and Sheets

# Combine tier selection with granular permission levels
uv run main.py --permissions gmail:organize drive:full --tool-tier core

📋 Credential Configuration


🧰 Available Tools

Note: All tools support automatic authentication via @require_google_service() decorators with 30-minute service caching.

📅 Google Calendar calendar_tools.py

Tool Tier Description
list_calendars Core List accessible calendars
get_events Core Retrieve events with time range filtering
manage_event Core Create, update, or delete calendar events
create_calendar Extended Create a new secondary Google Calendar
query_freebusy Extended Query free/busy information for calendars
manage_out_of_office Extended Create, list, update, or delete Out of Office events
manage_focus_time Extended Create, list, update, or delete Focus Time events

📁 Google Drive drive_tools.py

Tool Tier Description
search_drive_files Core Search files with query syntax
get_drive_file_content Core Read file content (Office, PDF, image)
get_drive_file_download_url Core Download Drive files to local disk
create_drive_file Core Create files or fetch from URLs
create_drive_folder Core Create empty folders in Drive or shared drives
import_to_google_doc Core Import files (MD, DOCX, HTML, etc.) as Google Docs
import_to_google_slides Core Import presentation files (PPTX, PPT, ODP) as Google Slides
import_to_google_sheets Core Import spreadsheet files (XLSX, CSV, TSV, etc.) as Google Sheets
get_drive_shareable_link Core Get shareable links for a file
list_drive_items Extended List folder contents or shared drives
copy_drive_file Extended Copy existing files (templates) with optional renaming
update_drive_file Extended Update metadata, move files, or replace Google Apps content
manage_drive_access Extended Grant, update, revoke permissions, and transfer ownership
set_drive_file_permissions Extended Set link sharing and file-level sharing settings
get_drive_file_permissions Complete Get file metadata, parents, and permissions
check_drive_file_public_access Complete Check public sharing status

📧 Gmail gmail_tools.py

Tool Tier Description
search_gmail_messages Core Search with Gmail operators
get_gmail_message_content Core Retrieve message content
get_gmail_messages_content_batch Core Batch retrieve message content
send_gmail_message Core Send emails
get_gmail_thread_content Extended Get full thread content
modify_gmail_message_labels Extended Modify message labels
list_gmail_labels Extended List available labels
list_gmail_filters Extended List Gmail filters
manage_gmail_label Extended Create/update/delete labels
manage_gmail_filter Extended Create or delete Gmail filters
draft_gmail_message Extended Create drafts
get_gmail_threads_content_batch Complete Batch retrieve thread content
batch_modify_gmail_message_labels Complete Batch modify labels
start_google_auth Complete Legacy OAuth 2.0 auth (disabled when OAuth 2.1 is enabled)

📝 Google Docs docs_tools.py

Tool Tier Description
get_doc_content Core Extract document text
create_doc Core Create new documents
modify_doc_text Core Insert, replace, and richly format text with tab/segment targeting, append-to-segment support, advanced typography, and link management
search_docs Extended Find documents by name
find_and_replace_doc Extended Find and replace text
list_docs_in_folder Extended List docs in folder
insert_doc_elements Extended Add tables, lists, page breaks
update_paragraph_style Extended Apply advanced paragraph styling including headings, spacing, direction, pagination controls, shading, and bulleted/numbered/checkbox lists with nesting
get_doc_as_markdown Extended Export document as formatted Markdown with optional comments
insert_doc_image Complete Insert images from Drive/URLs
update_doc_headers_footers Complete Create or update headers and footers with correct segment-aware writes
batch_update_doc Complete Execute atomic multi-step Docs API operations including named ranges, section breaks, document/section layout, header/footer creation, segment-aware inserts, images, tables, and rich formatting
inspect_doc_structure Complete Analyze document structure, including safe insertion points, tables, section breaks, headers/footers, and named ranges
export_doc_to_pdf Extended Export document to PDF
create_table_with_data Complete Create data tables
debug_table_structure Complete Debug table issues
list_document_comments Complete List all document comments
manage_document_comment Complete Create, reply to, or resolve comments
manage_doc_tab Complete Create, rename, delete, or populate tabs from markdown

📊 Google Sheets sheets_tools.py

Tool Tier Description
read_sheet_values Core Read cell ranges
modify_sheet_values Core Write/update/clear cells
create_spreadsheet Core Create new spreadsheets
list_spreadsheets Extended List accessible spreadsheets
get_spreadsheet_info Extended Get spreadsheet metadata
format_sheet_range Extended Apply colors, number formats, text wrapping, alignment, bold/italic, font size
list_sheet_tables Extended List structured tables with IDs, names, ranges, and columns
create_sheet Complete Add sheets to existing files
move_sheet_rows Complete Move rows between sheets within a spreadsheet
append_table_rows Complete Append rows to a structured table, auto-extending the table range
list_spreadsheet_comments Complete List all spreadsheet comments
manage_spreadsheet_comment Complete Create, reply to, or resolve comments
manage_conditional_formatting Complete Add, update, or delete conditional formatting rules

🖼️ Google Slides slides_tools.py

Tool Tier Description
create_presentation Core Create new presentations
get_presentation Core Retrieve presentation details
batch_update_presentation Extended Apply multiple updates
get_page Extended Get specific slide information
get_page_thumbnail Extended Generate slide thumbnails
list_presentation_comments Complete List all presentation comments
manage_presentation_comment Complete Create, reply to, or resolve comments

📋 Google Forms forms_tools.py

Tool Tier Description
create_form Core Create new forms
get_form Core Retrieve form details & URLs
set_publish_settings Complete Configure form settings
get_form_response Complete Get individual responses
list_form_responses Extended List all responses with pagination
batch_update_form Complete Apply batch updates (questions, settings)

✓ Google Tasks tasks_tools.py

Tool Tier Description
list_tasks Core List tasks with filtering
get_task Core Retrieve task details
manage_task Core Create, update, delete, or move tasks
list_task_lists Complete List task lists
get_task_list Complete Get task list details
manage_task_list Complete Create, update, delete task lists, or clear completed tasks

👤 Google Contacts contacts_tools.py

Tool Tier Description
search_contacts Core Search contacts by name, email, phone
get_contact Core Retrieve detailed contact info
list_contacts Core List contacts with pagination
manage_contact Core Create, update, or delete contacts
list_contact_groups Extended List contact groups/labels
get_contact_group Extended Get group details with members
manage_contacts_batch Complete Batch create, update, or delete contacts
manage_contact_group Complete Create, update, delete groups, or modify membership

💬 Google Chat chat_tools.py

Tool Tier Description
list_spaces Extended List chat spaces/rooms
get_messages Core Retrieve space messages
send_message Core Send messages to spaces
search_messages Core Search across chat history
create_reaction Core Add emoji reaction to a message
download_chat_attachment Extended Download attachment from a chat message

🔍 Google Custom Search search_tools.py

Tool Tier Description
search_custom Core Perform web searches (supports site restrictions via sites parameter)
get_search_engine_info Complete Retrieve search engine metadata

⚡ Google Apps Script apps_script_tools.py

Tool Tier Description
list_script_projects Core List accessible Apps Script projects
get_script_project Core Get complete project with all files
get_script_content Core Retrieve specific file content
create_script_project Core Create new standalone or bound project
update_script_content Core Update or create script files
run_script_function Core Execute function with parameters
list_deployments Extended List all project deployments
manage_deployment Extended Create, update, or delete script deployments
list_script_processes Extended View recent executions and status

Tool Tier Legend:Core — Essential tools for basic functionality · Minimal API usage · Getting started ● Extended — Core + additional features · Regular usage · Expanded capabilities ● Complete — All available tools including advanced features · Power users · Full API access


Connect to Claude Desktop

The recommended way to use Google Workspace MCP with Claude Desktop is to run a server instance and connect Claude to it via a Connector. This provides proper OAuth flow, multi-user support, and the best experience.

See the Quick Start Guide for setup instructions.

Connect to LM Studio

Add a new MCP server in LM Studio (Settings → MCP Servers) using the same JSON format:

{
  "mcpServers": {
    "google_workspace": {
      "command": "uvx",
      "args": ["workspace-mcp"],
      "env": {
        "GOOGLE_OAUTH_CLIENT_ID": "your-client-id",
        "GOOGLE_OAUTH_CLIENT_SECRET": "your-secret",
        "OAUTHLIB_INSECURE_TRANSPORT": "1",
      }
    }
  }
}

2. Advanced / Cross-Platform Installation

If you’re developing, deploying to servers, or using another MCP-capable client, keep reading.

Instant CLI (uvx)

Local Development Setup

OAuth 2.1 Support (Multi-User Bearer Token Authentication)

The server includes OAuth 2.1 support for bearer token authentication, enabling multi-user session management. OAuth 2.1 automatically reuses your existing GOOGLE_OAUTH_CLIENT_ID and, for confidential clients, GOOGLE_OAUTH_CLIENT_SECRET credentials - no additional Google-side configuration needed. Public PKCE clients are also supported: if you omit GOOGLE_OAUTH_CLIENT_SECRET, set FASTMCP_SERVER_AUTH_GOOGLE_JWT_SIGNING_KEY explicitly.

When to use OAuth 2.1:

  • Multiple users accessing the same MCP server instance
  • Need for bearer token authentication instead of passing user emails
  • Building web applications or APIs on top of the MCP server
  • Production environments requiring secure session management
  • Browser-based clients requiring CORS support

⚠️ Important: Mutually exclusive authentication modes

OAuth 2.1 mode (MCP_ENABLE_OAUTH21=true) cannot be used together with --single-user or service account mode:

  • Single-user mode: For legacy clients that pass user emails in tool calls
  • OAuth 2.1 mode: For modern multi-user scenarios with bearer token authentication
  • Service account mode: For headless/server-to-server use via domain-wide delegation

Choose one authentication method - combining incompatible modes will result in a startup error.

Enabling OAuth 2.1: To enable OAuth 2.1, set the MCP_ENABLE_OAUTH21 environment variable to true.

# OAuth 2.1 requires HTTP transport mode
export MCP_ENABLE_OAUTH21=true
uv run main.py --transport streamable-http

If MCP_ENABLE_OAUTH21 is not set to true, the server uses legacy authentication. In streamable-http mode, legacy authentication binds to 127.0.0.1 by default to keep cached Google credentials local. Set WORKSPACE_MCP_HOST explicitly only for trusted networks; use OAuth 2.1 for remote or shared HTTP deployments.

Streamable HTTP requests with an Origin header are checked against loopback origins, WORKSPACE_EXTERNAL_URL, and OAUTH_ALLOWED_ORIGINS to reduce DNS-rebinding risk. Non-browser MCP clients that omit Origin are unaffected.

vscode-webview origins: Origins with the vscode-webview:// scheme are scoped per-extension using the authority component (e.g. vscode-webview://publisher.extension). Adding a vscode-webview URI to OAUTH_ALLOWED_ORIGINS permits only the specific extension identified by that authority; other extensions are rejected.

Stateless Mode (Container-Friendly)

The server supports a stateless mode designed for containerized environments where file system writes should be avoided:

Enabling Stateless Mode:

# Stateless mode requires OAuth 2.1 to be enabled
export MCP_ENABLE_OAUTH21=true
export GOOGLE_OAUTH_CLIENT_ID="..."
export WORKSPACE_MCP_STATELESS_MODE=true
uv run main.py --transport streamable-http

Key Features:

  • No file system writes: Credentials are never written to disk
  • No debug logs: File-based logging is completely disabled
  • Memory-only sessions: All tokens stored in memory via OAuth 2.1 session store
  • Container-ready: Perfect for Docker, Kubernetes, and serverless deployments
  • Token per request: Each request must include a valid Bearer token

Requirements:

  • Must be used with MCP_ENABLE_OAUTH21=true
  • Incompatible with single-user mode
  • Clients must handle OAuth flow and send valid tokens with each request

This mode is ideal for:

  • Cloud deployments where persistent storage is unavailable
  • Multi-tenant environments requiring strict isolation
  • Containerized applications with read-only filesystems
  • Serverless functions and ephemeral compute environments

MCP Inspector: No additional configuration needed with desktop OAuth client.

Claude Code: No additional configuration needed with desktop OAuth client.

OAuth Proxy Storage Backends

The server supports pluggable storage backends for OAuth proxy state management via FastMCP 2.13.0+. Choose a backend based on your deployment needs.

Available Backends:

Backend Best For Persistence Multi-Server
Memory Development, testing
Disk Single-server production
Valkey/Redis Distributed production

Configuration:

# Memory storage (fast, no persistence)
export WORKSPACE_MCP_OAUTH_PROXY_STORAGE_BACKEND=memory

# Disk storage (persists across restarts)
export WORKSPACE_MCP_OAUTH_PROXY_STORAGE_BACKEND=disk
export WORKSPACE_MCP_OAUTH_PROXY_DISK_DIRECTORY=~/.fastmcp/oauth-proxy

# Valkey/Redis storage (distributed, multi-server)
export WORKSPACE_MCP_OAUTH_PROXY_STORAGE_BACKEND=valkey
export WORKSPACE_MCP_OAUTH_PROXY_VALKEY_HOST=redis.example.com
export WORKSPACE_MCP_OAUTH_PROXY_VALKEY_PORT=6379

Disk support requires workspace-mcp[disk] (or py-key-value-aio[disk]) when installing from source. The official Docker image includes the disk extra by default. Valkey support is optional. Install workspace-mcp[valkey] (or py-key-value-aio[valkey]) only if you enable the Valkey backend. Windows: building valkey-glide from source requires MSVC C++ build tools with C11 support. If you see aws-lc-sys C11 errors, set CFLAGS=/std:c11.

External OAuth 2.1 Provider Mode

The server supports an external OAuth 2.1 provider mode for scenarios where authentication is handled by an external system. In this mode, the MCP server does not manage the OAuth flow itself but expects valid bearer tokens in the Authorization header of tool calls.

Enabling External OAuth 2.1 Provider Mode:

# External OAuth provider mode requires OAuth 2.1 to be enabled
export MCP_ENABLE_OAUTH21=true
export GOOGLE_OAUTH_CLIENT_ID="..."
export EXTERNAL_OAUTH21_PROVIDER=true
uv run main.py --transport streamable-http

How It Works:

  • Protocol-level auth enabled: All MCP requests (including initialize and tools/list) require a valid Bearer token, following the standard OAuth 2.1 flow. Unauthenticated requests receive a 401 with resource metadata pointing to Google’s authorization server.
  • External OAuth flow: Your external system handles the OAuth flow and obtains Google access tokens (ya29.*)
  • Token validation: Server validates bearer tokens by calling Google’s userinfo API
  • Multi-user support: Each request is authenticated independently based on its bearer token
  • Resource metadata discovery: The server serves /.well-known/oauth-protected-resource (RFC 9728) advertising Google as the authorization server and the required scopes

Key Features:

  • No local OAuth flow: Server does not provide /authorize, /token, or /register endpoints — only resource metadata
  • Bearer token only: All authentication via Authorization: Bearer headers
  • Stateless by design: Works seamlessly with WORKSPACE_MCP_STATELESS_MODE=true
  • External identity providers: Integrate with your existing authentication infrastructure

Requirements:

  • Must be used with MCP_ENABLE_OAUTH21=true
  • OAuth client ID still required for token validation; client secret is optional for public clients (GOOGLE_OAUTH_CLIENT_ID, optional GOOGLE_OAUTH_CLIENT_SECRET)
  • External system must obtain valid Google OAuth access tokens (ya29.*)
  • Each tool call request must include valid bearer token

Use Cases:

  • Integrating with existing authentication systems
  • Custom OAuth flows managed by your application
  • API gateways that handle authentication upstream
  • Multi-tenant SaaS applications with centralized auth
  • Mobile or web apps with their own OAuth implementation

Service Account Mode (Domain-Wide Delegation)

WARNING: This mode uses Google Workspace domain-wide delegation, which grants the service account the ability to impersonate any user in your domain for the configured scopes. This is powerful and dangerous — do not use this unless you fully understand the security implications. A misconfigured service account with broad scopes can read, modify, and delete data across every user in your organization. Only use this in tightly controlled environments where you know exactly what you’re doing.

Service account mode allows the server to authenticate using a Google Cloud service account with domain-wide delegation instead of interactive OAuth flows. The service account impersonates a single configured domain user for all API calls.

When to use service account mode:

  • Headless or unattended environments where no browser is available for OAuth consent
  • Server-to-server integrations that need to act on behalf of a specific domain user
  • CI/CD pipelines or automation scripts
  • Environments where you cannot or do not want to manage per-user OAuth tokens

Enabling Service Account Mode:

# Option 1: Key file on disk
export GOOGLE_SERVICE_ACCOUNT_KEY_FILE="/path/to/service-account-key.json"
export USER_GOOGLE_EMAIL="[email protected]"
uv run main.py

# Option 2: Inline JSON key (e.g., from a secret manager)
export GOOGLE_SERVICE_ACCOUNT_KEY_JSON='{"type":"service_account","project_id":"...","private_key":"...","client_email":"..."}'
export USER_GOOGLE_EMAIL="[email protected]"
uv run main.py

Prerequisites:

  1. A Google Cloud service account with a JSON key
  2. Domain-wide delegation enabled for the service account in your Google Workspace Admin Console (Security → API controls → Domain-wide delegation)
  3. The required OAuth scopes authorized for the service account’s client ID in the Admin Console
  4. USER_GOOGLE_EMAIL set to the domain user the service account will impersonate

Incompatibilities:

  • Cannot be combined with --single-user mode
  • Cannot be combined with MCP_ENABLE_OAUTH21=true
  • Only one key source may be provided — set either GOOGLE_SERVICE_ACCOUNT_KEY_FILE or GOOGLE_SERVICE_ACCOUNT_KEY_JSON, not both

Key Behaviors:

  • The OAuth callback server is not started (no interactive auth needed)
  • Credentials directory permission checks are skipped
  • When a tool call supplies user_google_email, service account mode uses that email as the domain-wide delegation impersonation subject.
  • USER_GOOGLE_EMAIL is still required and serves as the fallback when no caller email is provided.
  • The service account key is validated at startup (checks for required fields and correct type)

Per-Request Impersonation:

The caller-supplied user_google_email on each tool call is used as the DWD impersonation subject instead of the static USER_GOOGLE_EMAIL. This lets a single server instance act on behalf of multiple domain users.

# Optional: restrict which domains may be impersonated
export DWD_ALLOWED_DOMAINS="corp.com,subsidiary.io"
  • If DWD_ALLOWED_DOMAINS is set, only emails whose domain appears in the comma-separated list are accepted; all others raise an authentication error.
  • If DWD_ALLOWED_DOMAINS is unset, any email accepted by the service account’s delegation scope is allowed.

VS Code MCP Client Support

✅ Recommended: VS Code MCP extension properly supports the full MCP specification. Always use HTTP transport mode for proper OAuth 2.1 authentication.

Claude Code MCP Client Support

✅ Recommended: Claude Code is a modern MCP client that properly supports the full MCP specification. Always use HTTP transport mode with Claude Code for proper OAuth 2.1 authentication and multi-user support.

Reverse Proxy Setup

If you’re running the MCP server behind a reverse proxy (nginx, Apache, Cloudflare, etc.), you have two configuration options:

Problem: When behind a reverse proxy, the server constructs OAuth URLs using internal ports (e.g., http://localhost:8000) but external clients need the public URL (e.g., https://your-domain.com).

Solution 1: Set WORKSPACE_EXTERNAL_URL for all OAuth endpoints:

# This configures all OAuth endpoints to use your external URL
export WORKSPACE_EXTERNAL_URL="https://your-domain.com"

Solution 2: Set GOOGLE_OAUTH_REDIRECT_URI for just the callback:

# This only overrides the OAuth callback URL
export GOOGLE_OAUTH_REDIRECT_URI="https://your-domain.com/oauth2callback"

You also have options for: | OAUTH_CUSTOM_REDIRECT_URIS (optional) | Comma-separated list of additional redirect URIs | | OAUTH_ALLOWED_ORIGINS (optional) | Comma-separated list of additional CORS origins |

Important:

  • Use WORKSPACE_EXTERNAL_URL when all OAuth endpoints should use the external URL (recommended for reverse proxy setups)

  • Use GOOGLE_OAUTH_REDIRECT_URI when you only need to override the callback URL

  • The redirect URI must exactly match what’s configured in your Google Cloud Console

  • Your reverse proxy must forward OAuth-related requests (/oauth2callback, /oauth2/*, /.well-known/*) to the MCP server

  • Do not set Referrer-Policy: no-referrer on your proxy. It makes browsers send Origin: null on the same-origin consent POST, which origin validation rejects with {"error": "Origin not allowed"} (logged as Rejected HTTP request from Origin: null) even when WORKSPACE_EXTERNAL_URL is correct. Use strict-origin-when-cross-origin (the browser default) or same-origin instead.

  • Some clients send Origin: null on the consent POST even with correct headers — Chrome serializes the form origin as opaque after the cross-origin OAuth redirect chain (seen with the Claude Code CLI flow). If you hit this, strip only a literal null Origin for the /consent endpoint. The consent endpoint is CSRF-protected by its unguessable txn_id, and nginx sends the empty-valued Origin header as an empty value that ASGI decodes to b""; the middleware validates only when raw_origin is truthy, so empty bytes skip this request while real origins still pass through and get validated:

    location ^~ /consent {
        set $consent_origin $http_origin;
        if ($http_origin = "null") { set $consent_origin ""; }
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Origin $consent_origin;
        proxy_pass http://127.0.0.1:;
    }
    

Requires Python 3.10+ and uvx. The package is available on PyPI.

Development Installation

For development or customization:

git clone https://github.com/taylorwilsdon/google_workspace_mcp.git
cd google_workspace_mcp
uv run main.py

Development Installation (For Contributors):

HTTP Mode (For debugging or web interfaces)

If you need to use HTTP mode with Claude Desktop:

{
  "mcpServers": {
    "google_workspace": {
      "command": "npx",
      "args": ["mcp-remote", "http://localhost:8000/mcp"]
    }
  }
}

Note: Make sure to start the server with --transport streamable-http when using HTTP mode. For remote or shared HTTP endpoints, also enable OAuth 2.1 with MCP_ENABLE_OAUTH21=true and GOOGLE_OAUTH_CLIENT_ID.

First-Time Authentication

Legacy local authentication uses the Google OAuth consent flow. In stdio mode, the server tries to open the browser automatically so long Google OAuth URLs do not wrap in terminals or get corrupted during copy/paste, which improves reliability of the redirect flow.

  • In stdio mode, the server starts a local callback listener and tries to open the Google authorization page in your browser automatically.
  • If the browser cannot be opened, the tool response includes the authorization URL to open manually.
  • In streamable-http / OAuth 2.1 mode, use your MCP client’s OAuth flow instead; the server does not try to open a browser on the host running the HTTP service.
  • When a legacy local auth tool call provides user_google_email, the server adds that value as login_hint on the Google authorization URL so Google can pre-select the account on the consent screen. This applies to the stdio flow whether the server opens the browser or returns the URL; streamable-http / OAuth 2.1 flows still rely on the MCP client’s OAuth flow.

Example:

user_google_email="[email protected]"
Authorization URL: https://accounts.google.com/o/oauth2/v2/auth?...&login_hint=alex%40example.com

When calling a tool:

  1. If an opened browser page appears, complete Google authorization there.
  2. If no browser opens, open the returned authorization URL manually and complete Google authorization there.
  3. After successful authorization, the callback page displays the authenticated email address.
  4. Retry the original tool call with that email as user_google_email; the server needs this value to associate the stored Google credentials with the tool request, so the original request is not authorized until it is retried.
  5. Server completes authentication using the stored Google credentials.

◆ Development

Project Structure

google_workspace_mcp/
├── auth/              # Authentication system with decorators
├── core/              # MCP server and utilities
├── g{service}/        # Service-specific tools
├── main.py            # Server entry point
├── client_secret.json # OAuth credentials (not committed)
└── pyproject.toml     # Dependencies

Adding New Tools

from auth.service_decorator import require_google_service

@require_google_service("drive", "drive_read")  # Service + scope group
async def your_new_tool(service, param1: str, param2: int = 10):
    """Tool description"""
    # service is automatically injected and cached
    result = service.files().list().execute()
    return result  # Return native Python objects

Architecture Highlights

  • Service Caching: 30-minute TTL reduces authentication overhead
  • Scope Management: Centralized in SCOPE_GROUPS for easy maintenance
  • Error Handling: Native exceptions instead of manual error construction
  • Multi-Service Support: @require_multiple_services() for complex tools

Credential Store System

The server includes an abstract credential store API with pluggable backends for managing Google OAuth credentials:

Features:

  • Abstract Interface: CredentialStore base class defines standard operations (get, store, delete, list users)
  • Local File Storage: LocalDirectoryCredentialStore — plaintext JSON files protected by filesystem permissions (0o600 / 0o700)
  • GCS-Backed Storage: GCSCredentialStore — stores each user’s credentials as an object in a Google Cloud Storage bucket. Supports atomic read-modify-write via generation preconditions, first-class Cloud IAM / Audit Logs integration, and transparent bucket-level CMEK encryption at rest
  • Configurable Storage: Environment variables select backend and location
  • Multi-User Support: Store and manage credentials for multiple Google accounts
  • Automatic Directory Creation: Storage directory is created automatically if it doesn’t exist (local backend)

Configuration:

# Install the optional dependency if you plan to use the GCS backend:
# uv sync --extra gcs
# or: pip install "workspace-mcp[gcs]"
#
# Select backend (default: local_directory). Supported: local_directory, gcs
export WORKSPACE_MCP_CREDENTIAL_STORE_BACKEND="gcs"

# --- local_directory options ---
export WORKSPACE_MCP_CREDENTIALS_DIR="/path/to/credentials"
# Backward-compatible alias:
export GOOGLE_MCP_CREDENTIALS_DIR="/path/to/credentials"

# Default directory locations (if no directory env var is set):
# - ~/.google_workspace_mcp/credentials (if home directory accessible)
# - ./.credentials (fallback)

# --- gcs options ---
export WORKSPACE_MCP_GCS_BUCKET="my-workspace-mcp-tokens"   # required
export WORKSPACE_MCP_GCS_PREFIX="credentials/"              # optional
export WORKSPACE_MCP_GCS_REQUIRE_CMEK="true"                # optional; see below

Backend selection:

  • local_directory (default): Plaintext JSON records. Suitable for local development and single-user stdio mode. Existing pre-URL-encoding local credential filenames remain readable during migration; new writes use the URL-encoded filename mapping unless a legacy file already exists for that user.
  • gcs: Stores credentials as objects in a GCS bucket using the JSON API. Authenticates via Application Default Credentials — on Cloud Run this means the runtime service account needs roles/storage.objectUser (or equivalent) on the bucket. Does not support list_users() — designed for multi-user OAuth 2.1 mode where users are looked up individually by email.

CMEK enforcement (gcs backend):

By default GCS encrypts objects with Google-managed keys. For customer-managed encryption, set a default KMS key on the bucket (e.g. via Terraform’s google_storage_bucket.encryption.default_kms_key_name). All credentials written to the bucket will inherit the key transparently — no application-level key to manage.

To guard against accidentally deploying against a bucket without CMEK, set WORKSPACE_MCP_GCS_REQUIRE_CMEK=true. The store will verify the bucket has a default KMS key at startup and refuse to initialize otherwise. Note that this check reads bucket metadata, so the runtime service account additionally needs storage.buckets.get — grant roles/storage.bucketViewer on the bucket (or a custom role containing storage.buckets.get) in addition to the object-level role. roles/storage.objectUser alone covers only object operations.

Usage Example:

from auth.credential_store import get_credential_store, LocalDirectoryCredentialStore

# Get the global credential store instance
store = get_credential_store()

# Store credentials for a user
store.store_credential("[email protected]", credentials)

# Retrieve credentials
creds = store.get_credential("[email protected]")

# List all users with stored credentials (local_directory backend only;
# GCSCredentialStore intentionally does not support enumeration — use the
# upstream identity provider to enumerate users instead).
if isinstance(store, LocalDirectoryCredentialStore):
    users = store.list_users()

The credential store automatically handles credential serialization, expiry parsing, and provides error handling for storage operations.


⊠ Security

  • Prompt Injection: This MCP server has the capability to retrieve your email, calendar events and drive files. Those emails, events and files could potentially contain prompt injections - i.e. hidden white text that tells it to forward your emails to a different address. You should exercise caution and in general, only connect trusted data to an LLM!
  • Credentials: Never commit .env, client_secret.json or the .credentials/ directory to source control!
  • OAuth Callback: Uses http://localhost:8000/oauth2callback for development (requires OAUTHLIB_INSECURE_TRANSPORT=1). If another process is already using port 8000, set WORKSPACE_MCP_PORT to a free port to avoid conflicts — e.g. export WORKSPACE_MCP_PORT=8123. If you use a web/confidential OAuth client (not the recommended Desktop client), also update the redirect URI in Google Cloud Console to match the new port (e.g. http://localhost:8123/oauth2callback); Desktop and PKCE clients do not require this.
  • Transport-Aware Callbacks: Stdio mode starts a minimal HTTP server only for OAuth, ensuring callbacks work in all modes
  • Production: Use HTTPS & OAuth 2.1 and configure accordingly
  • Scope Minimization: Tools request only necessary permissions
  • Local File Access Control: Tools that read local files (e.g., attachments, file:// uploads) are restricted to the managed attachment directory by default. Override this with the ALLOWED_FILE_DIRS environment variable if you intentionally need broader access:
    # Colon-separated list of directories (semicolon on Windows) from which local file reads are permitted
    export ALLOWED_FILE_DIRS="/home/user/documents:/data/shared"
    
    The managed attachment directory is controlled by WORKSPACE_ATTACHMENT_DIR and remains allowed even when ALLOWED_FILE_DIRS is set. Regardless of the allowlist, access to sensitive paths (.env, .ssh/, .aws/, /etc/shadow, credential files, etc.) is always blocked.
  • Indirect Prompt Injection: In agentic clients, email bodies, documents, and calendar events can contain malicious instructions that try to coerce the model into exfiltrating local files. Do not broaden ALLOWED_FILE_DIRS unless you trust the client, the model behavior, and the data sources it can read.


≡ License

MIT License - see LICENSE file for details.


Validations:

View this README on GitHub

Установка

uvx workspace-mcp

Конфигурация

{ "mcpServers": { "google_workspace": { "command": "uvx", "args": ["workspace-mcp"], "env": { "GOOGLE_OAUTH_CLIENT_ID": "your-client-id", "GOOGLE_OAUTH_CLIENT_SECRET": "your-secret", "OAUTHLIB_INSECURE_TRANSPORT": "1" } } } }