如何将内部 Cloud Run MCP 服务器安全地连接到 Gemini Enterprise
原题How to securely connect internal Cloud Run MCP servers to Gemini Enterprise
读前速览
本文介绍如何使用 Egress Agent Gateway、Private Service Connect 和限定 FQDN 的 Private Cloud DNS,将内部 Cloud Run MCP 服务器安全地连接到 Gemini Enterprise,解决内部入口、双重身份验证和 DNS 冲突等难题。
企业部署 MCP 服务器必须解决三项安全与网络挑战
仅允许内部访问的入口限制、双重身份验证(Cloud Run IAM + OAuth 2.0),以及 Shared VPC 环境中的 DNS 冲突规避,是阻碍原型 MCP 服务器投入生产的核心难题。
Egress Agent Gateway 搭配 PSC Network Attachment,可为无服务器 Cloud Run 实现 VPC 私有路由
该架构通过桥接 1(PSC Network Attachment)将托管网络接口接入 VPC,再通过桥接 2(Private Google Access 或 Global PSC Endpoint)将数据包以私有方式路由到 Cloud Run 的无服务器前端,从而满足内部入口规则。
限定 FQDN 的 Private Cloud DNS 可避免 Shared VPC 环境中的 DNS 冲突
方案不会覆盖整个 *.run.app 域名,而是仅为特定 MCP 服务的 FQDN 创建私有 DNS 区域。通过最长后缀匹配,其他 Cloud Run 服务仍可正常进行 DNS 解析,同时 MCP 服务器也能使用私有路由。
双标头身份验证可同时验证基础设施身份和用户身份
X-Serverless-Authorization 标头包含由 Google 签名的 OIDC ID 令牌,由 Cloud Run IAM 在边缘进行验证;Authorization Bearer 标头则携带用户的 OAuth 2.0 访问令牌,用于应用层权限控制。
GitHub 上提供了包含配置脚本的参考实现
配套代码库提供完整的 Python StreamableHTTP Cloud Run MCP 服务器,包括 OAuth 2.0 验证中间件、Dockerfile,以及适用于两种 VPC 路由选项的分步配置脚本。
完整摘要
本文详细介绍了将 Gemini Enterprise 连接到内部 Cloud Run MCP 服务器的安全架构,并解决三个关键难题:阻止服务暴露于公网、实施双层身份验证(Cloud Run IAM 和 OAuth 2.0),以及避免 Shared VPC 环境中的 DNS 冲突。该方案采用 Agent-to-Anywhere 模式的 Egress Agent Gateway、Private Service Connect Network Attachment,以及限定 FQDN 的 Private Cloud DNS。文中介绍了两种 VPC 路由选项:子网级 Private Google Access(199.36.153.8/30)和 Google APIs 的 Global PSC Endpoint(240.0.0.10)。这一架构确保 Gemini Enterprise 的请求通过 Egress Agent Gateway 以私有方式路由;网关解析 MCP 服务器的 FQDN,并将数据包注入 VPC,同时保留 TLS SNI 和 HTTP Host 标头。Cloud Run IAM 通过 X-Serverless-Authorization 标头验证基础设施层身份,而应用代码则验证用户的 OAuth 2.0 Bearer 令牌。GitHub 上还提供了包含 Python 中间件和配置脚本的参考实现。
目录 · 12 节
采用 Gemini Enterprise 的企业团队正越来越多地构建自定义模型上下文协议(MCP)服务器,将 AI 智能体连接到内部 API、数据库和业务工作流。Google Cloud Run 非常适合托管这类轻量级 StreamableHTTP MCP 服务器:它能够自动扩缩容、开箱即用地管理 TLS 证书,并与 Cloud IAM 原生集成。Enterprise teams adopting Gemini Enterprise are increasingly building custom Model Context Protocol (MCP) servers to connect AI agents with internal APIs, databases, and business workflows. Google Cloud Run is a natural fit for hosting these lightweight StreamableHTTP MCP servers: it scales automatically, manages TLS certificates out of the box, and integrates natively with Cloud IAM.
然而,将自定义 MCP 服务器从初始原型迁移到企业级生产环境,会立即面临三个现实中的安全与网络挑战:However, moving a custom MCP server from an initial prototype to an enterprise production environment immediately introduces three real-world security and networking challenges:
- 不暴露于公共互联网(仅限内部入口):企业安全策略要求内部 MCP 服务器阻止所有公共互联网流量,并且仅接受来自私有虚拟私有云 (VPC) 网络的请求。在 Cloud Run 上启用内部入口后,来自 Gemini Enterprise 的默认公共调用会在 Google 边缘被拒绝,并返回 HTTP 404。No public internet exposure (internal-only ingress): Enterprise security policies require internal MCP servers to block all public internet traffic and accept requests only from private Virtual Private Cloud (VPC) networks. When internal ingress is enabled on Cloud Run, default public calls from Gemini Enterprise are rejected at Google's edge with HTTP 404.
- 服务和用户身份验证(Cloud Run IAM + OAuth 2.0):生产环境部署要求对每次工具调用执行两项相互独立的身份验证。Cloud Run IAM 必须验证网络请求是否来自您获授权的 Gemini Enterprise 实例;您的 MCP 应用代码必须在代表已登录的人类用户执行操作前,验证其 OAuth 2.0 访问令牌的签名。Service and user authentication (Cloud Run IAM + OAuth 2.0): Production deployments require two independent identity checks on every tool call. Cloud Run IAM must verify that the network request originated from your authorized Gemini Enterprise instance, and your MCP application code must validate the signed-in human user's OAuth 2.0 access token before acting on their behalf.
- 扩展 Shared VPC 规模且避免 DNS 冲突:大型企业通常会在集中式 Shared(Hub)VPC 中运行数百个 Cloud Run 服务。为单个 MCP 服务器在 Private Cloud DNS 中覆盖整个 *.run.app 域,可能会劫持 DNS 解析,并破坏该网络中其他 Cloud Run 服务的路由。Shared VPC scale without DNS collisions: Large enterprises often run hundreds of Cloud Run services across a centralized Shared (Hub) VPC. Overriding the entire *.run.app domain in Private Cloud DNS for a single MCP server can hijack DNS resolution and break routing for other Cloud Run services across that network.
以下介绍如何使用 Egress Agent Gateway、Private Service Connect (PSC) 和按 FQDN 限定范围的 Private Cloud DNS 解决全部三个挑战,并提供 GitHub 上可运行的参考实现和设置脚本。Here is how you can solve all three challenges using Egress Agent Gateway, Private Service Connect (PSC), and FQDN-scoped Private Cloud DNS, complete with a runnable reference implementation and setup scripts on GitHub.
私有路径的工作原理How the private path works
将 Gemini Enterprise(运行在 Google 管理的租户项目中)连接到内部无服务器 Cloud Run MCP 服务器,需要打通两个网络跃点,并进行一次范围限定的 DNS 查询:Connecting Gemini Enterprise (which runs in a Google-managed tenant project) to an internal serverless Cloud Run MCP server requires bridging two network hops and one scoped DNS lookup:
在此架构中,Google Cloud 的三种网络和身份机制协同工作:Three Google Cloud networking and identity mechanisms work together in this architecture:
1. 双桥接私有 VPC 路由(PSC 网络附件 + PGA 或用于 Google API 的 PSC)1. Two-bridge private VPC routing (PSC Network Attachment + PGA or PSC for Google APIs)
与子网内具有内部 IP 地址的 Compute Engine 虚拟机不同,Cloud Run 是无服务器的。因此,私有路由需要通过两个桥接来实现:Unlike a Compute Engine VM with an internal IP address inside your subnet, Cloud Run is serverless. Private routing therefore uses two bridges:
- 桥接 1(通过 PSC 网络附件接入您的 VPC):处于 Agent-to-Anywhere 模式的区域级出站代理网关会连接到您区域子网(us-central1 或 europe-west1)中的 PSC 网络附件。这样,您的 VPC 内便会部署一个托管网络接口,无需公共 IP 或入站防火墙规则。Bridge 1 (Into your VPC via PSC Network Attachment): A regional Egress Agent Gateway in Agent-to-Anywhere mode connects to a PSC Network Attachment in your regional subnet (us-central1 or europe-west1). This places a managed network interface inside your VPC without public IPs or inbound firewall rules.
- Bridge 2 (From your VPC to Serverless Cloud Run): Once the packet enters your VPC subnet, it must reach Google's serverless Cloud Run frontend privately so Cloud Run recognizes the source VPC and satisfies internal ingress rules. Depending on your enterprise VPC design, you can use either:
- Option A: Subnet Private Google Access (199.36.153.8/30): Uses Google's built-in Private Google Access virtual IPs with zero extra VPC endpoints (recommended for standard VPCs that retain the default 0.0.0.0/0 route to the default internet gateway).
- Option B: Global PSC Endpoint for Google APIs (240.0.0.10): Uses a global internal IP address and forwarding rule targeting Google's built-in all-apis bundle (which includes Cloud Run with no internal load balancer or service attachment needed on the Cloud Run side). Google Cloud automatically injects a dedicated /32 internal route into your VPC, so private Cloud Run routing works even in locked-down VPCs where the 0.0.0.0/0 default internet route is deleted.
2. 按 FQDN 限定的私有云 DNS 解析(适用于共享 VPC)2. FQDN-scoped Private Cloud DNS resolution (safe for Shared VPCs)
当 Egress Agent Gateway 收到发往你的 Cloud Run MCP 服务器 URL 的工具调用时,它会在将数据包注入 VPC 之前解析一次主机名。如果没有 Private Cloud DNS,公共 DNS 会将 .run.app 域名解析为公共互联网 IP 地址,而这些地址会导致请求超时(HTTP 502),因为 PSC Network Attachment 不会将流量路由到公共互联网。When the Egress Agent Gateway receives a tool call for your Cloud Run MCP server URL, it resolves the hostname once before injecting the packet into your VPC. Without Private Cloud DNS, public DNS resolves .run.app domains to public internet IPs, which time out (HTTP 502) because a PSC Network Attachment does not route out to the public internet.
不要创建通配符 *.run.app 私有区域(这会覆盖 Shared VPC 中所有 Cloud Run 服务的 DNS 解析),而是创建一个仅限定于 MCP 服务确切完全限定域名(FQDN)的 Private Cloud DNS 区域,并且只将该域名与 Agent Gateway 对等连接。由于 Cloud DNS 使用最长后缀匹配,Shared VPC 中的其他所有 Cloud Run 服务仍会照常解析。与此同时,Agent Gateway 会向私有 VIP(199.36.153.8 或 240.0.0.10)发起 HTTPS 连接,同时在 TLS SNI 和 HTTP Host 标头中保留 Cloud Run 服务主机名,以便 Cloud Run 将请求路由到指定容器。Instead of creating a wildcard *.run.app private zone, which would override DNS resolution for every Cloud Run service in a Shared VPC, you create a Private Cloud DNS zone scoped exclusively to your MCP service's exact fully qualified domain name (FQDN) and peer only that domain with the Agent Gateway. Because Cloud DNS uses longest-suffix matching, every other Cloud Run service in your Shared VPC continues resolving normally. Meanwhile, the Agent Gateway opens its HTTPS connection to the private VIP (199.36.153.8 or 240.0.0.10) while preserving your Cloud Run service hostname in the TLS SNI and HTTP Host header so Cloud Run routes the request to your exact container.
3. 双重标头服务与用户身份3. Dual-header service and user identity
连接到 Cloud Run MCP 服务器 URL 时,Gemini Enterprise 会在每个请求中发送两个不同的授权标头:When connecting to a Cloud Run MCP server URL, Gemini Enterprise sends two distinct authorization headers on every request:
- 基础设施层(X-Serverless-Authorization 标头):包含一个由 Google 签名的 OIDC ID 令牌,供项目的 Gemini Enterprise 服务代理使用。Cloud Run IAM 会在无服务器边缘根据 Cloud Run Invoker 角色验证此令牌,并在请求到达容器之前移除该标头。Infrastructure layer (X-Serverless-Authorization header): Contains a Google-signed OIDC ID token for your project's Gemini Enterprise service agent. Cloud Run IAM verifies this token against the Cloud Run Invoker role at the serverless edge and strips the header before the request reaches your container.
- 应用层(Authorization Bearer 标头):原样包含已登录用户的 OAuth 2.0 访问令牌,使 MCP 服务器内部的中间件能够验证调用者的身份并实施按用户划分的权限控制。Application layer (Authorization Bearer header): Contains the signed-in user's OAuth 2.0 access token untouched, allowing middleware inside your MCP server to verify the caller's identity and enforce per-user permissions.
class OAuth2ValidationMiddleware(BaseHTTPMiddleware):
"""Validates the end-user OAuth 2.0 Bearer token on incoming MCP requests."""
async def dispatch(self, request: Request, call_next) -> Response:
if request.url.path == "/health":
return await call_next(request)
has_serverless_auth = "x-serverless-authorization" in request.headers
auth_header = request.headers.get("authorization", "")
if auth_header.lower().startswith("bearer "):
raw_token = auth_header.split(" ", 1)[1].strip()
verified = await _verify_google_oauth_token(raw_token)
if verified is None and REQUIRE_OAUTH:
return JSONResponse(
{"error": "Invalid or expired OAuth 2.0 Bearer token."},
status_code=401,
)
elif REQUIRE_OAUTH:
return JSONResponse(
{"error": "Missing Authorization: Bearer <token> header."},
status_code=401,
)
return await call_next(request)
配置集成的 5 个步骤5 steps to configure the integration
我们的配套 GitHub 仓库通过一系列依次执行的设置脚本和逐步的 Cloud Console 操作说明,实现了整个部署流程的自动化:Our companion GitHub repository automates the entire deployment into sequential setup scripts alongside step-by-step Cloud Console instructions:
第 1 步:限制 Cloud Run 的访问并授予服务调用者访问权限Step 1: Lock down Cloud Run and grant service invoker access
将你的 StreamableHTTP MCP 服务器部署到 Cloud Run,并启用仅限内部的入口流量和 IAM 身份验证;然后向项目的 Gemini Enterprise 服务代理授予 Cloud Run Invoker 角色,这样只有你的 Gemini Enterprise 实例才能调用该容器。Deploy your StreamableHTTP MCP server to Cloud Run with internal-only ingress and IAM authentication enabled, and grant the Cloud Run Invoker role to your project's Gemini Enterprise service agent so only your Gemini Enterprise instance can invoke the container.
步骤 2:配置 VPC、PSC 网络连接和出口代理网关Step 2: Provision the VPC, PSC Network Attachment, and Egress Agent Gateway
在区域 VPC 子网上启用 Private Google Access,并创建一个设置为自动接受连接的 Private Service Connect Network Attachment。接下来,创建一个处于 Agent-to-Anywhere 模式的 Google 托管出站代理网关,向自动创建的网关服务账号授予网络和 DNS 对等互连权限,附加网络附件,并应用出站授权策略。Enable Private Google Access on your regional VPC subnet and create a Private Service Connect Network Attachment set to accept connections automatically. Next, create a Google-managed Egress Agent Gateway in Agent-to-Anywhere mode, grant networking and DNS peering permissions to the auto-created gateway service accounts, attach your network attachment, and apply an outbound authorization policy.
步骤 3:配置限定 FQDN 的私有云 DNS 和 DNS 对等连接Step 3: Configure FQDN-scoped Private Cloud DNS and DNS peering
在 Cloud DNS 中,为你的 VPC 创建一个私有托管区域,仅包含 MCP 服务的确切 Cloud Run 主机名。将其 A 记录指向 Google 的 Private Google Access VIP(对于没有默认互联网路由的隔离 VPC,则指向内部 PSC 端点 IP),并在 Agent Gateway 上为该主机名配置 DNS 对等互连。In Cloud DNS, create a private managed zone attached to your VPC for only your MCP service's exact Cloud Run hostname. Point its A record to Google's Private Google Access VIPs (or to your internal PSC endpoint IP for isolated VPCs without a default internet route), and configure DNS peering on the Agent Gateway for that single hostname.
第 4 步:绑定 Agent Gateway,并在 Gemini Enterprise 中注册 MCP 服务器Step 4: Bind the Agent Gateway and register the MCP server in Gemini Enterprise
在 Gemini Enterprise 控制台的“安全配置”下,将 Egress Agent Gateway 绑定到你的应用。使用 Cloud Run 端点和 OAuth 2.0 客户端凭据注册 Custom MCP Server 数据存储,并在连接器上启用 Agent Gateway 出站流量和 Actions 模式。In the Gemini Enterprise console under Security Configuration, bind your Egress Agent Gateway to your app. Register your Custom MCP Server data store with your Cloud Run endpoint and OAuth 2.0 client credentials, and enable Agent Gateway egress and Actions mode on the connector.
步骤 5:在 Cloud Logging 中验证私有 MCP 调用Step 5: Verify private MCP calls in Cloud Logging
在控制台中重新加载自定义操作,并在 Gemini Enterprise Web 应用中运行测试提示。在 Cloud Logging 中,你可以验证工具初始化、发现和执行调用是否通过 Egress Agent Gateway 私有路由到内部 Cloud Run 容器,并且服务 IAM 和用户 OAuth 2.0 检查均已通过。Reload your custom actions in the console and run a test prompt in the Gemini Enterprise web app. In Cloud Logging, you can verify that tool initialization, discovery, and execution calls route privately through the Egress Agent Gateway to your internal Cloud Run container with both service IAM and user OAuth 2.0 checks passing.
后续步骤Next steps
要在您自己的 Google Cloud 项目中部署并测试这两种私有路由模式,请查看以下 GitHub 代码库:To deploy and test both private routing patterns in your own Google Cloud project, check out the GitHub repository for:
- 一个完整的 Python StreamableHTTP Cloud Run MCP 服务器,包含 OAuth 2.0 验证中间件、Dockerfile 和本地冒烟测试。A complete Python StreamableHTTP Cloud Run MCP server with OAuth 2.0 validation middleware, Dockerfile, and local smoke tests.
- 涵盖选项 A(子网私有 Google 访问)和选项 B(Google API 的全局 PSC 端点)的分步设置脚本和 Cloud Console 界面操作说明,包括 Shared VPC IAM 绑定和 Cloud Logging 验证。Step-by-step setup scripts and Cloud Console UI instructions covering both Option A (Subnet Private Google Access) and Option B (Global PSC Endpoint for Google APIs), including Shared VPC IAM bindings and Cloud Logging verification.
相关文档Related documentation
- 在 Gemini Enterprise 中设置自定义 MCP 服务器数据存储
- 设置具有 VPC 连接能力的自定义 MCP 服务器数据存储的前提条件
- 为 Agent Gateway 设置 VPC 连接不中返
- 限制 Cloud Run 的入站流量
- 服务的私有访问选项