mcp-google-oauth

mcp-google-oauth

MCP server with built-in Google OAuth 2.0 authentication, enabling secure tool access via Google sign-in with automatic token lifecycle management and optional domain restriction for Google Workspace organizations.

Category
访问服务器

README

MCP Server with Google OAuth 2.0 Authentication

Building an MCP server is straightforward — but adding proper authentication is not. The MCP spec requires OAuth 2.0 with discovery endpoints, dynamic client registration, PKCE, and token lifecycle management. That's a lot of boilerplate before you can write your first tool.

This project gives you all of that out of the box. You focus on your tools, authentication is handled.

pip install mcp-google-oauth

Prerequisite: This implementation uses Google OAuth 2.0 and is designed for organizations with Google Workspace. Your company domain (e.g. yourcompany.com) must be managed by Google Workspace to restrict access to internal users. Other identity providers (Microsoft Entra ID, Okta, etc.) can be implemented following the same OAuth 2.0 methodology used here.

Why use this

For developers building MCP servers:

  • Authentication is the hardest part of MCP integration — this eliminates it entirely
  • One function call (create_mcp_app()) sets up the full OAuth 2.0 stack
  • You only write @mcp.tool() functions — everything else is provided
  • Works with Claude Desktop, Claude.ai, and any MCP-compatible client

For end users connecting to your MCP server:

  • Sign in with Google — no API tokens, no secrets, no config files to manage
  • Browser opens automatically on first use, then stays authenticated for 30 days
  • Access is controlled by Google Workspace domain (e.g. only @yourcompany.com)

What's included

  • Google OAuth 2.0 sign-in with optional domain restriction
  • Token management (1hr access tokens, 30-day refresh, auto-renewal)
  • Full MCP protocol compliance (OAuth discovery, client registration, PKCE)
  • Health check at /health

A complete MCP server in 15 lines

# main.py
from dotenv import load_dotenv
load_dotenv()
from mcp_auth import create_mcp_app, MCPAuthConfig

config = MCPAuthConfig.from_env()
config.mcp_name = "my-connector"

app, mcp = create_mcp_app(config)

@mcp.tool()
def hello(name: str = "world") -> str:
    """Say hello."""
    return f"Hello, {name}!"

How It Works

graph LR
    subgraph Claude
        C[Claude Desktop<br/>or claude.ai]
        MR[mcp-remote]
        C <--> MR
    end

    subgraph Server ["Your Server"]
        AUTH[mcp_auth/<br/>OAuth + token mgmt]
        TOOLS["main.py<br/>@mcp.tool()"]
        DB[(Database<br/>OAuth tokens only)]
        AUTH <--> DB
    end

    subgraph Auth ["Authentication Provider"]
        G[Google OAuth 2.0]
    end

    MR <-->|HTTPS| AUTH
    MR <-->|tool calls| TOOLS
    AUTH <-->|verify identity| G

Auth Flow

sequenceDiagram
    participant C as Claude
    participant S as Your Server
    participant G as Google

    C->>S: POST /mcp/
    S-->>C: 401 Unauthorized

    C->>S: Discover OAuth endpoints
    S-->>C: OAuth metadata

    C->>S: Register client
    S-->>C: client_id + secret

    C->>S: Authorize
    S-->>C: Redirect to Google
    C->>G: User signs in

    G-->>S: Callback + code
    Note over S: Validate domain

    S-->>C: Auth code
    C->>S: Exchange code
    S-->>C: Access + refresh tokens

    C->>S: POST /mcp/ + Bearer token
    S-->>C: Tool result
  • Access tokens expire in 1 hour (auto-refreshed by Claude)
  • Refresh tokens last 30 days
  • Domain restriction enforced at /google/callback
  • PKCE (S256) and HMAC-signed state prevent CSRF

See docs/architecture.md for detailed diagrams.


Quick Start

1. Install

Requires Python 3.11+. Check with python3 --version. If needed: brew install python@3.13 (macOS) or see python.org.

pip install mcp-google-oauth

Or install from source:

git clone https://github.com/hungvietdo/mcp-google-oauth.git
cd mcp-google-oauth
python3 -m venv .venv && source .venv/bin/activate
pip install -e .

2. Create your MCP server

Create a main.py in a new directory with your tools:

# main.py
from dotenv import load_dotenv
load_dotenv()

from mcp_auth import create_mcp_app, MCPAuthConfig

config = MCPAuthConfig.from_env()
config.mcp_name = "my-connector"
config.mcp_instructions = "A custom MCP connector."

app, mcp = create_mcp_app(config)


@mcp.tool()
def hello(name: str = "world") -> str:
    """Say hello. Use this to verify the connection is working."""
    return f"Hello, {name}!"


# Add your own tools below...

3. Set up Google OAuth credentials

  1. Go to Google Cloud Console
  2. APIs & Services → OAuth consent screen
    • User Type: Internal (restricts to your Google Workspace org)
    • Fill in app name + contact email → Save
  3. APIs & Services → Credentials → Create Credentials → OAuth 2.0 Client ID
    • Application type: Web application
    • Authorized redirect URI: https://YOUR_DOMAIN/google/callback
  4. Copy Client ID and Client Secret

4. Configure environment

Create a .env file in the same directory as main.py:

SESSION_SECRET=<run: python3 -c "import secrets; print(secrets.token_hex(32))">
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
ALLOWED_DOMAIN=yourcompany.com
DATABASE_URL=sqlite:///./local.db
MCP_ISSUER_URL=https://your-domain.ngrok.app/mcp
GOOGLE_MCP_CALLBACK_URL=https://your-domain.ngrok.app/google/callback

5. Run

mcp-google-oauth

Options:

mcp-google-oauth --port 9000          # custom port (default: 8080)
mcp-google-oauth --reload             # auto-reload on file changes (dev mode)
mcp-google-oauth --app mymodule:app   # custom app module (default: main:app)

Exposing to the internet: Claude.ai requires a public HTTPS URL. Use ngrok to tunnel your local server:

ngrok http 8080 --domain=your-domain.ngrok.app

Update MCP_ISSUER_URL and GOOGLE_MCP_CALLBACK_URL in .env to match the ngrok URL, then restart.

6. Connect from Claude

Claude.ai (Pro/Max/Team/Enterprise) — go to Customize → Connectors → Add custom connector and paste your MCP server URL. Either format works:

  • https://your-domain.ngrok.app/mcp/
  • https://your-domain.ngrok.app/

First use opens your browser for Google sign-in. No tokens or config files needed on the client side.

Claude Desktop / Claude Code: Add the server to your MCP config. See Claude MCP docs for details.


Project Structure

├── pyproject.toml           # Package definition — pip install mcp-google-oauth
├── main.py                  # Your MCP server — define tools here
├── .env.example             # Template for credentials
│
├── mcp_auth/                # Installable auth package
│   ├── __init__.py          # create_mcp_app() + MCPAuthConfig
│   ├── cli.py               # mcp-google-oauth CLI entrypoint
│   ├── database.py          # SQLAlchemy engine + session
│   ├── models.py            # OAuth token tables (auto-created)
│   ├── oauth_provider.py    # Google OAuth 2.0 provider
│   ├── middleware.py        # Path rewrite fix for mcp-remote
│   ├── routes.py            # /google/callback, /health
│   └── example_main.py     # Starter template
│
└── docs/
    └── architecture.md      # Detailed diagrams (OAuth flow, data model, security)

Configuration

Environment Variables

Variable Required Description
GOOGLE_CLIENT_ID Yes From Google Cloud Console
GOOGLE_CLIENT_SECRET Yes From Google Cloud Console
GOOGLE_MCP_CALLBACK_URL Yes https://your-domain/google/callback
MCP_ISSUER_URL Yes https://your-domain/mcp
SESSION_SECRET Yes Random hex string for signing sessions
ALLOWED_DOMAIN No Restrict to a Google Workspace domain (e.g. yourcompany.com)
DATABASE_URL No Default: sqlite:///./local.db

Why a database? The database only stores OAuth access and refresh tokens. It does not store any application data. Tables are auto-created on startup. If the database is deleted, users simply re-authenticate with Google on their next request — no data is lost.

MCPAuthConfig Properties

Set in code after MCPAuthConfig.from_env():

Property Default Description
mcp_name "mcp-server" MCP server name shown in Claude
mcp_instructions "" Instructions for Claude about available tools

Troubleshooting

pip: command not found

Use pip3 or python3 -m pip instead:

pip3 install mcp-google-oauth
# or
python3 -m pip install mcp-google-oauth

mcp-google-oauth: command not found after install

The CLI is installed into your Python's bin directory. If it's not on your PATH, run it directly:

python3 -m mcp_auth.cli

Or find where pip installs scripts:

python3 -m site --user-base  # add /bin to your PATH

No main.py found in the current directory

Run mcp-google-oauth from the directory that contains your main.py, or pass the app explicitly:

mcp-google-oauth --app mymodule:app

Google OAuth callback error / redirect URI mismatch

The redirect URI in Google Cloud Console must exactly match GOOGLE_MCP_CALLBACK_URL in your .env. Check for trailing slashes or http vs https mismatches.

Access blocked: domain not allowed

Your Google account's email domain doesn't match ALLOWED_DOMAIN. Either:

  • Sign in with the correct Google Workspace account
  • Remove ALLOWED_DOMAIN from .env to allow any Google account

Claude says "Failed to connect" or times out

  • Confirm the server is running: curl https://your-domain/health should return {"status":"ok"}
  • Confirm MCP_ISSUER_URL matches the URL you give Claude (including /mcp suffix)
  • If using ngrok, confirm the tunnel is active and the domain hasn't changed

Token expired / need to re-authenticate

Access tokens auto-refresh. If re-auth is needed (e.g. after deleting the database), just reconnect the server in Claude — it will open the browser again.

ImportError or missing dependencies

Make sure you installed into the right Python environment:

python3 -m pip install mcp-google-oauth

If using a virtual environment, activate it first before installing and running.


License

MIT

推荐服务器

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 模型以安全和受控的方式获取实时的网络信息。

官方
精选