How to secure remote MCP servers on Cloud Run with OAuth 2.0 PKCE

Local Model Context Protocol (MCP) servers running over stdio read API keys straight from environment variables. That shortcut breaks the moment you deploy a remote MCP server over HTTPS for hundreds of employees. When every caller shares one static API key or service account, your backend loses per-user permissions and audit trails.

In this guide, we compare the five OAuth 2.0 options teams consider for remote MCP servers, explain why pre-registered 3-legged OAuth with PKCE fits corporate identity providers, and deploy a working Python server on Cloud Run wired into Gemini on Google Cloud.

Which OAuth 2.0 pattern should you pick for remote MCP?

Most onboarding blockers when deploying remote MCP servers come down to OAuth mismatches. Teams often copy a flow designed for local desktop clients or nightly batch jobs and hit a wall during security review.

OAuth Mechanism Best Fit Enterprise IdP Support Production Verdict
3LO Auth Code + PKCE (S256) + Pre-Registered Client Internal IT, regulated APIs, EHRs (SMART on FHIR) Broad (Okta, Entra ID, Auth0, Identity Platform) (Recommended) Broad support with per-user RBAC
3LO Auth Code + PKCE (S256) + Dynamic Client Reg (RFC 7591) Multi-tenant SaaS MCP catalogs Low in enterprise IT (POST /register often disabled) Strong for SaaS vendors, blocked by most corporate IdPs
OAuth Token Exchange (RFC 8693) Internal microservices on one corporate IdP Medium (requires pre-configured IdP trust) Good for single-org internal hops without extra prompts
Client ID Metadata Documents (CIMD) Desktop and IDE MCP clients Very low in enterprise IdPs Avoid standalone (needs /register or pre-registration)
2LO client_credentials (private_key_jwt) Headless nightly batch pipelines High for machine-to-machine jobs Avoid for interactive agents (breaks user RBAC)

For production, 3-legged OAuth 2.0 Authorization Code with PKCE (S256), a pre-registered client, and RFC 9728 Protected Resource Metadata is a reliable default. Healthcare IT proved this model with SMART on FHIR by binding user tokens to a single resource URL (aud) so misrouted tokens fail. The MCP authorization specification uses the same RFC 9728 discovery and RFC 8707 resource indicator flow.

Architecture overview

Here is how the request flow works on Google Cloud. Agent Identity manages each caller’s OAuth 2.0 grant and refresh token, while Agent Gateway injects the Authorization: Bearer header at egress. Code inside Agent Sandbox stays isolated from raw user credentials.

Figure 1: Per-user 3LO OAuth 2.0 PKCE request flow using RFC 9728 discovery, Agent Identity, Agent Gateway, and JWKS validation on Cloud Run.

Step 1: Build the OAuth-protected MCP server in Python

Create a project folder for a fictional ticket service at Acme Corp (main.py). Because we mount FastMCP’s Streamable HTTP Starlette app under FastAPI to enforce auth middleware on every /mcp call (initialize, tools/list, and tools/call), we also start mcp.session_manager.run() inside FastAPI’s lifespan.

This service exposes two routes on Cloud Run:

  1. An RFC 9728 metadata endpoint (/.well-known/oauth-protected-resource) advertising your resource URL, trusted authorization servers, and scopes.
  2. An auth middleware layer that returns HTTP 401 with a WWW-Authenticate header on unauthenticated /mcp calls, verifies JSON Web Tokens (JWTs) against your identity provider’s JSON Web Key Set (JWKS), and checks audience (aud), issuer (iss), and scopes.
import contextlib
import os
import jwt
from jwt import PyJWKClient
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from mcp.server.fastmcp import FastMCP
from mcp.types import ToolAnnotations

RESOURCE_URL = os.environ["MCP_RESOURCE_URL"]  # e.g. https://acme-tickets-mcp-uc.a.run.app/mcp
AUTH_ISSUER = os.environ["OAUTH_ISSUER"]       # e.g. https://auth.acme.example
JWKS_URL = os.environ["OAUTH_JWKS_URL"]        # e.g. https://auth.acme.example/.well-known/jwks.json

jwks_client = PyJWKClient(JWKS_URL)
mcp = FastMCP("acme-tickets", stateless_http=True)

@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True, destructiveHint=False))
def get_ticket(ticket_id: str) -> dict:
    """Fetch live status and owner for a support ticket."""
    return {"ticket_id": ticket_id, "status": "OPEN", "owner": "sre-oncall@acme.example"}

@mcp.tool(annotations=ToolAnnotations(readOnlyHint=False, destructiveHint=False))
def create_ticket(title: str, severity: str) -> dict:
    """Create a staged support ticket after human confirmation."""
    return {"ticket_id": "INC-4092", "title": title, "severity": severity, "state": "CREATED"}

mcp_app = mcp.streamable_http_app()

@contextlib.asynccontextmanager
async def lifespan(app: FastAPI):
    async with mcp.session_manager.run():
        yield

app = FastAPI(lifespan=lifespan)

@app.get("/.well-known/oauth-protected-resource")
async def oauth_protected_resource():
    return {
        "resource": RESOURCE_URL,
        "authorization_servers": [AUTH_ISSUER],
        "bearer_methods_supported": ["header"],
        "scopes_supported": ["tickets:read", "tickets:write"],
    }

@app.middleware("http")
async def verify_bearer_token(request: Request, call_next):
    if not request.url.path.startswith("/mcp"):
        return await call_next(request)

    metadata_url = f"{RESOURCE_URL.removesuffix('/mcp')}/.well-known/oauth-protected-resource"
    challenge = f'Bearer resource_metadata="{metadata_url}", scope="tickets:read"'
    auth_header = request.headers.get("authorization", "")

    if not auth_header.startswith("Bearer "):
        return JSONResponse({"error": "unauthorized"}, status_code=401, headers={"WWW-Authenticate": challenge})

    token = auth_header.removeprefix("Bearer ").strip()
    try:
        signing_key = jwks_client.get_signing_key_from_jwt(token)
        claims = jwt.decode(
            token,
            signing_key.key,
            algorithms=["RS256", "ES256"],
            audience=RESOURCE_URL,
            issuer=AUTH_ISSUER,
        )
        request.state.user_sub = claims.get("sub")
        request.state.scopes = set(claims.get("scope", "").split())
    except jwt.PyJWTError as exc:
        return JSONResponse({"error": str(exc)}, status_code=401, headers={"WWW-Authenticate": challenge})

    return await call_next(request)

app.mount("/", mcp_app)

Notice the ToolAnnotations on each tool. Marking get_ticket with readOnlyHint=True lets read lookups run smoothly, while readOnlyHint=False on create_ticket triggers a confirmation card at Agent Gateway before the call reaches Cloud Run.

Step 2: Deploy to Cloud Run and verify RFC 9728 discovery

Add fastapi, uvicorn, mcp, and PyJWT[crypto] to requirements.txt, plus a Procfile with web: uvicorn main:app --host 0.0.0.0 --port $PORT. Deploy from source with --allow-unauthenticated at the Cloud Run ingress layer so OAuth clients can reach /.well-known/oauth-protected-resource and receive the 401 challenge, while your middleware enforces valid user JWTs on every /mcp call:

gcloud run deploy acme-tickets-mcp \
  --source . \
  --region us-central1 \
  --allow-unauthenticated \
  --set-env-vars="MCP_RESOURCE_URL=https://acme-tickets-mcp-uc.a.run.app/mcp,OAUTH_ISSUER=https://auth.acme.example,OAUTH_JWKS_URL=https://auth.acme.example/.well-known/jwks.json"

Before touching any console UI, run two curl checks to verify your OAuth discovery contract:

# 1. Confirm unauthenticated POST /mcp returns 401 with WWW-Authenticate metadata pointer
curl -i -X POST https://acme-tickets-mcp-uc.a.run.app/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}'

# 2. Confirm Protected Resource Metadata returns 200 OK and matches your issuer
curl -s https://acme-tickets-mcp-uc.a.run.app/.well-known/oauth-protected-resource | jq .

Step 3: Connect your server and avoid four common OAuth traps

In your identity provider (Okta, Microsoft Entra ID, Auth0, or Identity Platform), create a confidential OAuth 2.0 Web Application client:

  1. Allowlist the callback URI: https://vertexaisearch.cloud.google.com/oauth-redirect.
  2. Enable Authorization Code grant with PKCE (S256) and Refresh Token (offline_access).
  3. Follow the steps to set up a custom MCP server under Connected Data Stores > New data store > Custom MCP Server, entering your /mcp URL, Authorization URL, Token URL, Client ID, Client Secret, and scopes (openid offline_access tickets:read tickets:write).

When testing your integration end to end, watch out for four production bugs we debug regularly:

  • Hiding 401 until tools/call: Some servers allow unauthenticated initialize and tools/list requests and only return 401 when a tool runs. Return 401 WWW-Authenticate on initialize too so OAuth discovery triggers right away.
  • Query strings on the Authorization URL: Enter a clean base Authorization URL (https://auth.acme.example/oauth2/authorize) without ?prompt=consent appended. Pass extra parameters in the dedicated auth parameters field so the client doesn’t produce a broken ?...? query string.
  • Public DCR clients failing Basic Auth: If you also expose RFC 7591 Dynamic Client Registration (POST /register) for public PKCE clients without a client_secret, declare "token_endpoint_auth_method": "none". Otherwise, sending an empty Basic Auth header to /token fails with 401 invalid_client.
  • Missing offline_access on refresh: Access tokens usually expire after an hour. If your identity provider doesn’t issue a refresh token or rejects grant_type=refresh_token, callers will hit expired sessions the next morning.

Next steps

Once your Cloud Run MCP server passes both curl checks and enforces per-user JWT scopes, tool calls are logged in Cloud Audit Logs and governed through Agent Gateway and Agent Identity.

To test this setup in your own Google Cloud project: