Labsco
taylorwilsdon logo

Google Workspace

β˜… 2,800

from taylorwilsdon

Integrates Google Workspace services like Calendar, Drive, and Gmail with AI assistants.

πŸ”₯πŸ”₯πŸ”₯πŸ”₯πŸ”₯βœ“ VerifiedAccount requiredAdvanced setup

Google Workspace MCP Server

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!

The most feature-complete Google Workspace MCP server, 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!

Support for all free Google accounts & Google Workspace plans (Starter, Standard, Plus, Enterprise, Non Profit) with expanded app options like Chat & Spaces. ** Interested in a private, managed cloud instance? That can be arranged.

⚑ 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.1 Β· Stateless External OAuth Β· Reverse Proxy

πŸ“ Develop****

Architecture Β· Dev Setup Security Β· License

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

πŸ“§ Gmail β€” Complete email management, end-to-end coverage πŸ“ Drive β€” File operations with sharing, permissions, Office files, PDFs & images πŸ“… Calendar β€” Full event management with advanced features πŸ“ Docs β€” Deep, fine-grained editing, formatting & comments πŸ“Š Sheets β€” Flexible cell management, formatting & conditional rules πŸ–ΌοΈ Slides β€” Presentation creation, updates & content manipulation πŸ“‹ Forms β€” Creation, publish settings & response management πŸ’¬ Chat β€” Space management, messaging & reactions

⚑ Apps Script β€” Cross-application workflow automation  Projects Β· deployments Β· versions Β· execution Β· debugging

βœ… Tasks β€” Task & list management with hierarchy πŸ‘€ Contacts β€” People API with groups & batch operations πŸ” Custom Search β€” Programmable Search Engine integration

πŸ” Authentication & Security OAuth 2.0 & 2.1 Β· auto token refresh Β· multi-user bearer tokens Β· transport-aware callbacks Β· CORS proxy

Security & Compliance

For Security Teams

This server sends no data anywhere except Google's APIs, on behalf of the authenticated user, using your own OAuth client credentials. There is no telemetry, no usage reporting, no analytics, no license server, and no SaaS dependency. The entire data path is: your infrastructure β†’ Google APIs.

  • Fully open source β€” every line is auditable in this repo

  • Your OAuth client, your GCP project β€” credentials never leave your environment

  • You control the scopes β€” read-only, granular per-service permissions, or full access

  • You control the network β€” deploy behind your reverse proxy, in your VPC, on your own terms

  • No third-party services β€” no intermediary servers, no token relays, no hosted backends

  • Stateless mode β€” zero disk writes for locked-down container environments

  • Sensitive path blocking β€” local file reads default to the managed attachment directory, and validate_file_path() still blocks .env* files plus common home-directory credential stores such as ~/.ssh/ and ~/.aws/ even if ALLOWED_FILE_DIRS is broadened

Full dependency tree in pyproject.toml, pinned in uv.lock.

For Legal & Procurement

This project is MIT licensed β€” not "open core," not "source available," not "free with a CLA." There is no dual licensing, no commercial tier gating features, and no contributor license agreement.

  • Use commercially without restriction β€” build products, sell services, deploy internally

  • Fork, embed, redistribute β€” MIT requires only attribution

  • No CLA β€” contributions remain under MIT

  • No telemetry to disclose β€” nothing to flag in a privacy review

  • No network effects β€” the server never contacts any endpoint you didn't configure

  • Standard dependency licenses β€” MIT, Apache 2.0, and BSD throughout the dependency chain; no copyleft, no AGPL

The license is 21 lines and says what it means.

🧰 Available Tools

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

πŸ“– Looking for detailed parameters? Visit the Complete Documentation β†’ for comprehensive tool reference, examples, and API guides!

πŸ“… 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)

πŸ“Ž Email Attachments** ← Send emails with files Both send_gmail_message and draft_gmail_message support attachments via two methods:

Option 1: File Path (local server only)

Copy & paste β€” that's it
attachments=[{"path": "/path/to/report.pdf"}]

Reads file from disk, auto-detects MIME type. Optional filename override.

Option 2: Base64 Content (works everywhere)

Copy & paste β€” that's it
attachments=[{
 "filename": "report.pdf",
 "content": "JVBERi0xLjQK...", # base64-encoded
 "mime_type": "application/pdf" # optional
}]

⚠️ Centrally Hosted Servers: When the MCP server runs remotely (cloud, shared instance), it cannot access your local filesystem. Use Option 2 with base64-encoded content. Your MCP client must encode files before sending.

πŸ“₯ Downloaded Attachment Storage ← Where downloaded files are saved When downloading Gmail attachments (get_gmail_attachment_content) or Drive files (get_drive_file_download_url), files are saved to a persistent local directory rather than a temporary folder in the working directory.

Default location: ~/.workspace-mcp/attachments/

Files are saved with their original filename plus a short UUID suffix for uniqueness (e.g., invoice_a1b2c3d4.pdf). In stdio mode, the tool returns the absolute file path for direct filesystem access. In HTTP mode, it returns a download URL via the /attachments/{file_id} endpoint.

To customize the storage directory:

Copy & paste β€” that's it
export WORKSPACE_ATTACHMENT_DIR="/path/to/custom/dir"

Saved files expire after 1 hour and are cleaned up automatically.

πŸ“ 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

πŸ’¬ Chat setup β€” required before any Chat tool works Unlike other Workspace services, enabling the Chat API is not enough β€” the Chat API refuses every request until you configure a Chat app, and it only works with Google Workspace accounts. Two extra steps are required:

1. Configure the Chat app

Enabling chat.googleapis.com alone causes every Chat tool to fail. You must also complete the Configuration tab so the API has an app identity to attach requests to:

  • Open Chat API β†’ Configuration (APIs & Services β†’ Enabled APIs β†’ Google Chat API β†’ Configuration)

  • Fill in the three required fields under Application info:

  • App name β€” e.g. Workspace MCP (up to 25 characters)

  • Avatar URL β€” any HTTPS URL to a square PNG/JPEG (e.g. https://developers.google.com/chat/images/quickstart-app-avatar.png)

  • Description β€” e.g. Workspace MCP (up to 40 characters)

  • Click Save

** This server authenticates as the signed-in user (user OAuth), not as a bot. You do not need to enable interactive features, create a service account, or publish the app β€” the Configuration form above is the only Chat-specific setup required.

  1. Use a Google Workspace account

The Chat API is not available to personal @gmail.com accounts . Configuring it with one returns:

Copy & paste β€” that's it
Google Chat API is only available to Google Workspace users.

Sign in with a Business/Enterprise Google Workspace account (the same account you pass as user_google_email).

The required scopes (chat.spaces.readonly, chat.messages.readonly, chat.messages, chat.spaces) are requested automatically during the OAuth flow β€” no manual scope configuration is needed.

Configure the Chat API β†’ Β· User authentication β†’

πŸ” 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.

πŸ“ Legacy: Manual stdio configuration** ← For clients without Connector support ** ⚠️ Note : Stdio mode is a legacy fallback for clients that don't support Connectors. Prefer the Connector-based approach above.

OAuth callback caveat : The legacy stdio callback path includes a local recovery fallback for rare Google redirects that omit the state parameter, but only when --single-user is active. That recovery can only be safe in a single-user local process; in HTTP or hosted multi-user scenarios it could consume another user's pending OAuth state. There is no environment variable to enable this globally.

Open Claude Desktop Settings β†’ Developer β†’ Edit Config

  • macOS : ~/Library/Application Support/Claude/claude_desktop_config.json

  • Windows : %APPDATA%\Claude\claude_desktop_config.json

Add the server configuration:

Copy & paste β€” that's it
{
 "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"
 }
 }
 }
}

Connect to LM Studio

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

Copy & paste β€” that's it
{
 "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)

⚑ Quick Start with uvx** ← No installation required!

Copy & paste β€” that's it
# Requires Python 3.10+ and uvx
# First, set credentials (see Credential Configuration above)
uvx workspace-mcp --tool-tier core # or --tools gmail drive calendar

** Note : Configure OAuth credentials before running. Supports environment variables, .env file, or client_secret.json.

Local Development Setup

πŸ› οΈ Developer Workflow** ← Install deps, lint, and test

Copy & paste β€” that's it
# Install everything needed for linting, tests, and release tooling
uv sync --group dev

# Run the same linter that git hooks invoke automatically
uv run ruff check .

# Execute the full test suite (async fixtures require pytest-asyncio)
uv run pytest
  • uv sync --group test installs only the testing stack if you need a slimmer environment.

  • MCP_ENABLE_OAUTH21=true GOOGLE_OAUTH_CLIENT_ID=... uv run main.py --transport streamable-http launches the HTTP server with your checked-out code for manual verification.

  • Ruff is part of the dev group because pre-push hooks call ruff check automaticallyβ€”run it locally before committing to avoid hook failures.

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.

Copy & paste β€” that's it
# 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.

πŸ” How the FastMCP GoogleProvider handles OAuth** ← Advanced OAuth 2.1 details FastMCP ships a native GoogleProvider that we now rely on directly. It solves the two tricky parts of using Google OAuth with MCP clients:

Dynamic Client Registration: Google still doesn't support OAuth 2.1 DCR, but the FastMCP provider exposes the full DCR surface and forwards registrations to Google using your fixed credentials. MCP clients register as usual and the provider hands them your Google client ID and, when configured, client secret under the hood.

CORS & Browser Compatibility: The provider includes an OAuth proxy that serves all discovery, authorization, and token endpoints with proper CORS headers. We no longer maintain custom /oauth2/* routesβ€”the provider handles the upstream exchanges securely and advertises the correct metadata to clients.

The result is a leaner server that still enables any OAuth 2.1 compliant client (including browser-based ones) to authenticate through Google without bespoke code.

Restricting DCR client redirect URIs:

By default, any client going through Dynamic Client Registration can declare any redirect_uri. For publicly-exposed deployments, this is a phishing vector β€” an attacker can register a client with a redirect_uri they control and harvest authorization codes from tricked users. Set WORKSPACE_MCP_ALLOWED_CLIENT_REDIRECT_URIS to a comma-separated allowlist of permitted URIs:

Copy & paste β€” that's it
# Public deployment β€” restrict to Claude's hosted OAuth callbacks
export WORKSPACE_MCP_ALLOWED_CLIENT_REDIRECT_URIS="https://claude.ai/api/mcp/auth_callback,https://claude.com/api/mcp/auth_callback"

# Add Claude Code CLI (loopback redirects on ephemeral ports)
export WORKSPACE_MCP_ALLOWED_CLIENT_REDIRECT_URIS="https://claude.ai/api/mcp/auth_callback,https://claude.com/api/mcp/auth_callback,http://localhost:*/callback,http://127.0.0.1:*/callback"

Patterns use FastMCP's matcher: * wildcards any port or path component; *.example.com matches subdomains. Leaving the variable unset preserves the default DCR behaviour (any URI accepted), which is appropriate for local development but unsafe for public deployments.

Stateless Mode (Container-Friendly)

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

Enabling Stateless Mode:

Copy & paste β€” that's it
# 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:

Copy & paste β€” that's it
# 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.

πŸ” Valkey/Redis Configuration Options**

Variable Default Description WORKSPACE_MCP_OAUTH_PROXY_VALKEY_HOST localhost Valkey/Redis host WORKSPACE_MCP_OAUTH_PROXY_VALKEY_PORT 6379 Port (6380 auto-enables TLS) WORKSPACE_MCP_OAUTH_PROXY_VALKEY_DB 0 Database number WORKSPACE_MCP_OAUTH_PROXY_VALKEY_USE_TLS auto Enable TLS (auto if port 6380) WORKSPACE_MCP_OAUTH_PROXY_VALKEY_USERNAME - Authentication username WORKSPACE_MCP_OAUTH_PROXY_VALKEY_PASSWORD - Authentication password WORKSPACE_MCP_OAUTH_PROXY_VALKEY_REQUEST_TIMEOUT_MS 5000 Request timeout for remote hosts WORKSPACE_MCP_OAUTH_PROXY_VALKEY_CONNECTION_TIMEOUT_MS 10000 Connection timeout for remote hosts

Encryption: Disk and Valkey storage are encrypted with Fernet. The encryption key is derived from FASTMCP_SERVER_AUTH_GOOGLE_JWT_SIGNING_KEY if set, otherwise from GOOGLE_OAUTH_CLIENT_SECRET. Public OAuth 2.1 client setups without a client secret must set FASTMCP_SERVER_AUTH_GOOGLE_JWT_SIGNING_KEY.

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:

Copy & paste β€” that's it
# 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 <token> 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:

Copy & paste β€” that's it
# 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:

  • A Google Cloud service account with a JSON key

  • Domain-wide delegation enabled for the service account in your Google Workspace Admin Console (Security β†’ API controls β†’ Domain-wide delegation)

  • The required OAuth scopes authorized for the service account's client ID in the Admin Console

  • 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.

Copy & paste β€” that's it
# 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.

πŸ†š VS Code Configuration** ← Setup for VS Code MCP extension

Copy & paste β€” that's it
{
 "servers": {
 "google-workspace": {
 "url": "http://localhost:8000/mcp/",
 "type": "http"
 }
 }
}

Note: Make sure to start the server with --transport streamable-http when using VS Code MCP. For remote or shared HTTP endpoints, see the OAuth 2.1 note in the HTTP Mode section .

** Origin validation : VS Code webview clients send a vscode-webview://<extension-id> origin, which is rejected by default. Add the specific origin to OAUTH_ALLOWED_ORIGINS (e.g. OAUTH_ALLOWED_ORIGINS=vscode-webview://your.extension-id) to permit it. Connections to a localhost/127.0.0.1 URL are allowed without extra configuration.

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.

πŸ†š Claude Code Configuration** ← Setup for Claude Code MCP support

Copy & paste β€” that's it
# Start the server in HTTP mode first
export MCP_ENABLE_OAUTH21=true
export GOOGLE_OAUTH_CLIENT_ID="..."
uv run main.py --transport streamable-http

# Then add to Claude Code
claude mcp add --transport http workspace-mcp http://localhost:8000/mcp

# Optional: install the bundled Claude skill for better Workspace tool routing
mkdir -p ~/.claude/skills
ln -s "$(pwd)/skills/managing-google-workspace" ~/.claude/skills/managing-google-workspace

Or copy skills/managing-google-workspace into ~/.claude/skills/managing-google-workspace if you prefer not to symlink it.

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:

Copy & paste β€” that's it
# 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:

Copy & paste β€” that's it
# 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_U