1. 简介
在此 Codelab 中,您将学习如何使用智能体开发套件 (ADK) 构建直接连接到官方 Google Workspace MCP 服务器的专业代码 AI 智能体。
Model Context Protocol (MCP) 是一种开放标准,可让 AI 模型安全地使用远程服务器提供的工具。ADK 是 Google 推出的专业代码框架,用于构建自主智能体。通过将它们结合使用,您可以创建高度定制化的智能体,并以 Gmail、Google 云端硬盘、Google 日历、Google Chat 和 Google 个人资料数据为依据。
如需查看有关可用工具和配置的完整文档,请参阅配置 Google Workspace MCP 服务器。
您将执行的操作
- 在 Google Cloud 项目中启用 Google Workspace MCP 服务。
- 配置 OAuth 同意并创建凭证,以便进行本地测试和生产部署。
- 构建一个本地 ADK 智能体,该智能体使用静态令牌连接到 Google Workspace MCP 服务器。
- 构建一个可用于生产用途的 ADK 智能体,并将其部署到 Gemini Enterprise Agent Platform (GEAP) Agent Runtime,该智能体使用动态令牌注入。
- 在 Gemini Enterprise 中原生注册和测试自定义智能体。
所需条件
- 网络浏览器(例如 Chrome)。
- 启用了结算功能的 Google Cloud 项目。
- Google Workspace 账号(已启用智能功能)。
- 在本地机器上安装了 Python 3.11+。
- 已安装并初始化 Google Cloud CLI (
gcloud)。
2. 准备工作
创建或选择 Google Cloud 项目
控制台选项
在 Google Cloud 控制台中,选择或创建 Google Cloud 项目。
CLI 选项
创建一个新项目并将其设为活跃项目:
gcloud projects create YOUR_PROJECT_ID
gcloud config set project YOUR_PROJECT_ID
启用 API
如需使用 Google Workspace MCP 服务器,您必须同时启用标准 Google Workspace API 和专用 MCP 服务。
控制台选项
点击以下按钮,即可使用网络浏览器启用它们:
CLI 选项:执行以下终端命令:
# Enable standard GWS APIs
gcloud services enable chat.googleapis.com \
drive.googleapis.com \
calendar-json.googleapis.com \
people.googleapis.com \
gmail.googleapis.com
# Enable dedicated MCP services
gcloud services enable calendarmcp.googleapis.com \
chatmcp.googleapis.com \
drivemcp.googleapis.com \
gmailmcp.googleapis.com \
workspacemcp.googleapis.com
配置 Chat 应用
如需使用 Google Chat MCP 服务器,您必须在 Google Cloud 项目中配置 Chat 应用。
3. 配置 OAuth 权限请求和客户端
Google Workspace MCP 服务器使用 OAuth 2.0 进行安全身份验证。您必须配置 OAuth 权限请求页面,并创建两个单独的客户端 ID:一个用于本地开发,另一个用于已部署的智能体。
设置 OAuth 权限请求页面
- 在 Google Cloud 控制台中,点击左上角的导航菜单(汉堡图标)。依次选择 Google Auth Platform > 品牌信息(如果看不到 Google Auth Platform,则依次选择 API 和服务 > OAuth 权限请求页面)。
- 配置应用信息:
- 应用名称:
Workspace ADK Agent - 用户支持邮箱:选择您的邮箱。
- 应用名称:
- 配置受众群体:选择内部。
- 配置联系信息:输入您的邮箱,然后点击创建。
- 依次前往数据访问权限 > 添加或移除范围。在手动添加范围下,添加以下范围以授予对所需服务的访问权限:
https://www.googleapis.com/auth/calendar.events https://www.googleapis.com/auth/calendar.calendars https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/chat.spaces https://www.googleapis.com/auth/chat.messages https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/gmail.compose https://www.googleapis.com/auth/directory.readonly https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/contacts.readonly https://www.googleapis.com/auth/cloud-platform - 依次点击添加到表格、更新和保存。
为本地开发创建客户端 ID(桌面应用)
为 Google Workspace MCP 服务器配置 OAuth 2.0 客户端时,您必须选择将此客户端用于 AI 赋能的智能体,以启用智能体分类设置 (is_agentic)。未启用此设置的 OAuth 客户端将无法调用 Google Workspace MCP 端点。
- 在 Google Cloud 控制台中,前往 Google Auth Platform > 客户端(或 API 和服务 > 凭证)。点击创建客户端(或创建凭证 > OAuth 客户端 ID)。
- 选择桌面应用作为应用类型。
- 将该文件命名为
Workspace Agent Local。 - 选择将此客户端用于 AI 赋能的智能体,以便在 OAuth 客户端上启用
is_agentic分类标志。 - 点击创建,然后下载 JSON 文件。在本地将其另存为
client_secret.json。
4. 智能体开发和测试
本部分介绍了如何构建智能体环境。我们将使用静态令牌方法进行测试,即使用 gcloud 提取 OAuth 令牌,并将其传递给 ADK 的 McpToolset。您可以使用本地机器或 Google Cloud Shell 按照以下步骤操作。
选择您的环境:本地机器或 Google Cloud Shell,以设置您的开发环境。这两种方法都将使用共享的 Python 脚本进行身份验证,以确保跨平台的一致性。
1. 设置环境目录
在终端中执行以下命令,以创建项目目录并安装所需的软件包。
- 对于 Google Cloud Shell:首先,点击 Google Cloud 控制台右上角工具栏中的激活 Cloud Shell 图标 (
>_)。 - 对于本地机器:打开标准终端。
mkdir -p gws-adk-agent/workspace_agent
cd gws-adk-agent
python3 -m venv .venv
source .venv/bin/activate
pip install google-adk poetry google-auth-oauthlib
2. 准备凭证文件
您必须将上一步中下载的 client_secret.json 文件放入 gws-adk-agent 目录的根目录中。
- 本地机器:将下载的
client_secret.json文件移动或复制到gws-adk-agent目录中。 - Google Cloud Shell:在 Cloud Shell 中运行以下命令来创建文件(将
[PASTE_JSON_HERE]替换为您的实际 JSON 内容):
cat << 'EOF' > client_secret.json
[PASTE_JSON_HERE]
EOF
3. 进行身份验证并生成 .env (auth.py)
为了以一致的方式处理身份验证并避免特定于环境的 CLI 路由问题,我们使用由官方 Google 身份验证库提供支持的自定义 Python 脚本。此脚本会管理 OAuth 流程,在本地保存应用默认凭证 (ADC),并生成所需的 .env 文件。
在 gws-adk-agent 目录中创建名为 auth.py 的文件,并添加以下代码:
import json
import os
from urllib.parse import urlparse, parse_qs
import google.auth
from google_auth_oauthlib.flow import InstalledAppFlow
CLIENT_SECRET_FILE = 'client_secret.json'
SCOPES = [
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/calendar",
"https://www.googleapis.com/auth/chat.spaces.readonly",
"https://www.googleapis.com/auth/chat.messages",
"https://www.googleapis.com/auth/drive.readonly",
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/gmail.compose",
"https://www.googleapis.com/auth/directory.readonly",
"https://www.googleapis.com/auth/contacts.readonly"
]
# Initialize the flow from the client secrets JSON
flow = InstalledAppFlow.from_client_secrets_file(
CLIENT_SECRET_FILE,
scopes=SCOPES,
redirect_uri='http://localhost:8085/'
)
# Generate the Auth URL
auth_url, expected_state = flow.authorization_url(prompt='consent', access_type='offline')
print("\n=== GOOGLE OAUTH OFFICIAL LIBRARY FLOW ===")
print("1. Copy the following link and paste it into your browser (or click it if supported):\n")
print(auth_url)
print("\n2. Authorize the application.")
print("3. Your browser will redirect to a 'localhost' page (it will show a 'Site can't be reached' error, which is EXPECTED and normal).")
print("4. Copy the ENTIRE URL from your browser's address bar (including the http://localhost:8085/ part).\n")
# Get the redirected URL from the user
redirected_url = input("Paste the full localhost URL here: ").strip()
# Exchange the redirect URL for tokens
print("\nExchanging code for tokens...")
try:
parsed_url = urlparse(redirected_url)
query_params = parse_qs(parsed_url.query)
returned_state = query_params.get('state', [None])[0]
code = query_params.get('code', [None])[0]
if not code:
raise ValueError("No 'code' parameter found in the URL.")
if returned_state != expected_state:
raise ValueError("CSRF Warning! State mismatch.")
flow.fetch_token(code=code)
creds = flow.credentials
except Exception as e:
print(f"Authentication failed: {e}")
exit(1)
if not creds.refresh_token:
print("\nError: No refresh token returned. You may need to revoke access and try again.")
exit(1)
# Save Application Default Credentials
adc_data = {
"client_id": creds.client_id,
"client_secret": creds.client_secret,
"refresh_token": creds.refresh_token,
"type": "authorized_user"
}
adc_dir = os.path.expanduser("~/.config/gcloud")
os.makedirs(adc_dir, exist_ok=True)
adc_path = os.path.join(adc_dir, "application_default_credentials.json")
with open(adc_path, "w") as f:
json.dump(adc_data, f, indent=2)
# Detect Project ID
try:
_, project_id = google.auth.default()
except Exception:
project_id = None
project_id = project_id or os.environ.get("GOOGLE_CLOUD_PROJECT", "YOUR_PROJECT_ID")
# Save to .env for local development (relative to project root)
env_dir = "workspace_agent"
os.makedirs(env_dir, exist_ok=True)
env_path = os.path.join(env_dir, ".env")
with open(env_path, "w") as f:
f.write("GOOGLE_GENAI_USE_VERTEXAI=1\n")
f.write(f"GOOGLE_CLOUD_PROJECT={project_id}\n")
f.write("GOOGLE_CLOUD_LOCATION=us-central1\n")
print(f"\nSuccess! Application Default Credentials saved to: {adc_path}")
print(f"Environment variables saved to: {env_path}")
if project_id == "YOUR_PROJECT_ID":
print("NOTE: Could not automatically detect Project ID. Please update it manually in .env")
在终端中运行该脚本:
python3 auth.py
创建代理代码
无论您在上一步中选择哪种环境,代理代码都完全相同。在预先创建的 workspace_agent 子目录中创建一个名为 agent.py 的文件,并添加以下代码。此脚本使用应用默认凭证 (ADC) 提供授权,通过动态标头提供程序在内存中自动验证和刷新凭证。
import os
import datetime
import google.auth
from google.auth.transport.requests import Request
from google.adk.agents.llm_agent import LlmAgent
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams
# Enable graceful error handling so timeouts return as tool outputs instead of crashing
os.environ["ADK_ENABLE_MCP_GRACEFUL_ERROR_HANDLING"] = "1"
MODEL = "gemini-2.5-flash"
# Inject User ADC path globally so both ADK and underlying GenAI SDKs
# load it safely, bypassing broken Compute Engine metadata fallbacks.
_adc_path = os.path.expanduser(
"~/.config/gcloud/application_default_credentials.json"
)
if not os.path.exists(_adc_path):
raise FileNotFoundError(
f"User ADC not found at {_adc_path}. "
"Please run 'python3 auth.py' first to generate credentials."
)
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = _adc_path
creds, _ = google.auth.default()
class TokenRelay:
"""Manages in-memory caching of Google OAuth access tokens.
Decouples token refresh logic from credentials validation states to
prevent infinite refresh loops during automated tool retries.
"""
def __init__(self, credentials):
self._creds = credentials
self._cached_token: str | None = None
self._expiry: datetime.datetime | None = None
def get_token(self) -> str:
now = datetime.datetime.now()
# Refresh if no cache or expiring within 5 minutes
if (
self._cached_token is None
or self._expiry is None
or now >= (self._expiry - datetime.timedelta(minutes=5))
):
self._creds.refresh(Request())
self._cached_token = self._creds.token
# Token lives for 60 mins; cache for 50 mins safely
self._expiry = now + datetime.timedelta(minutes=50)
print("\n[Agent Runtime] Access token refreshed from ADC.")
return self._cached_token or ""
# Initialize auth relay and perform startup safety check
token_relay = TokenRelay(creds)
token_relay.get_token()
def auth_header_provider(tool_context=None) -> dict[str, str]:
return {"Authorization": f"Bearer {token_relay.get_token()}"}
# Initialize the Google Workspace MCP servers with dynamic runtime provider
calendar_mcp = McpToolset(
connection_params=StreamableHTTPConnectionParams(
url="https://calendarmcp.googleapis.com/mcp/v1",
),
header_provider=auth_header_provider
)
chat_mcp = McpToolset(
connection_params=StreamableHTTPConnectionParams(
url="https://chatmcp.googleapis.com/mcp/v1",
),
header_provider=auth_header_provider
)
drive_mcp = McpToolset(
connection_params=StreamableHTTPConnectionParams(
url="https://drivemcp.googleapis.com/mcp/v1",
),
header_provider=auth_header_provider
)
gmail_mcp = McpToolset(
connection_params=StreamableHTTPConnectionParams(
url="https://gmailmcp.googleapis.com/mcp/v1",
),
header_provider=auth_header_provider
)
people_mcp = McpToolset(
connection_params=StreamableHTTPConnectionParams(
url="https://people.googleapis.com/mcp/v1",
),
header_provider=auth_header_provider
)
universal_search_mcp = McpToolset(
connection_params=StreamableHTTPConnectionParams(
url="https://workspacemcp.googleapis.com/mcp/v1",
),
header_provider=auth_header_provider
)
current_date = datetime.datetime.now().strftime("%Y-%m-%d")
# Define the agent and attach all configured toolsets
root_agent = LlmAgent(
model=MODEL,
name='gws_adk_agent',
instruction=f"""You are a helpful assistant grounded in the user's Google Workspace data.
Today's current date is {current_date}. Always calculate relative dates (like 'this week' or 'upcoming meetings') using this reference.
Use the provided MCP tools to answer questions about their Calendar, Chat, Drive, Gmail, Contacts, and perform Universal Search.
If a tool returns an error indicating a timeout, inform the user that the service took too long to respond.""",
tools=[calendar_mcp, chat_mcp, drive_mcp, gmail_mcp, people_mcp, universal_search_mcp]
)
运行和测试智能体
您可以使用交互式网页界面或直接在终端/Shell 中与智能体互动。
选项 1:交互式 Web 界面
如果您使用的是本地机器:
- 从
gws-adk-agent项目根目录启动 ADK 网页界面:adk web - 在浏览器中打开
http://localhost:8000,即可与智能体对话。
如果您使用的是 Google Cloud Shell:
- 在
gws-adk-agent项目根目录中,启动 ADK 网页界面,并明确强制使用端口 8080:adk web --port 8080 --allow_origins=* - 点击 Cloud Shell 工具栏右上角的网页预览按钮,然后选择在端口 8080 上预览,即可在新标签页中打开该界面。
选项 2:终端 CLI 模式(备选)
如果您更喜欢在终端中操作,或者不想设置网络浏览器预览,ADK 提供了原生的交互式 REPL 对话模式。
在 gws-adk-agent 项目根目录中,执行以下命令(在本地机器和 Google Cloud Shell 中,此命令的执行方式完全相同):
adk run workspace_agent
您将直接在 shell 中进入交互式聊天会话:
Running agent gws_adk_agent, type exit to exit.
[user]:
尝试向智能体发送提示
无论您选择哪种界面,都可以尝试使用利用 Workspace MCP 工具的查询来测试智能体:
What are my upcoming meetings this week?
Summarize the last 3 unread emails in my Gmail.
5. 生产环境部署
如需将代理部署到生产环境,我们不能使用硬编码的本地令牌。而是使用 ADK 的 header_provider,在用户与智能体互动时,动态提取 Gemini Enterprise 平台注入的 OAuth 访问令牌。
创建生产代理代码
创建一个名为 enterprise_ai 的目录软件包,并在其中创建一个 agent.py 文件:
mkdir -p enterprise_ai
将以下内容写入 enterprise_ai/agent.py:
import os
import datetime
import re
from google.adk.agents.llm_agent import LlmAgent
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams
from google.adk.tools.tool_context import ToolContext
# Enable graceful error handling so timeouts return as tool outputs instead of crashing
os.environ["ADK_ENABLE_MCP_GRACEFUL_ERROR_HANDLING"] = "1"
MODEL = "gemini-2.5-flash"
# This name MUST match the Authorization Name used during Gemini Enterprise registration
CLIENT_AUTH_NAME = "workspace-adk-auth"
def _get_access_token_from_context(tool_context: ToolContext) -> str:
"""Dynamically parses the user bearer token injected into the ToolContext state."""
escaped_name = re.escape(CLIENT_AUTH_NAME)
pattern = re.compile(fr"^{escaped_name}_\d+$")
state_dict = tool_context.state.to_dict() if hasattr(tool_context.state, 'to_dict') else tool_context.state
matching_keys = [k for k in state_dict.keys() if pattern.match(k)]
if matching_keys:
return state_dict.get(matching_keys[0])
raise Exception(f"No bearer token found in ToolContext state matching pattern {pattern.pattern}")
def auth_header_provider(tool_context: ToolContext) -> dict[str, str]:
"""Provides the dynamic Authorization header for MCP requests."""
token = _get_access_token_from_context(tool_context)
return {"Authorization": f"Bearer {token}"}
# Initialize toolsets using the dynamic header_provider
calendar_mcp = McpToolset(
connection_params=StreamableHTTPConnectionParams(url="https://calendarmcp.googleapis.com/mcp/v1"),
header_provider=auth_header_provider
)
chat_mcp = McpToolset(
connection_params=StreamableHTTPConnectionParams(url="https://chatmcp.googleapis.com/mcp/v1"),
header_provider=auth_header_provider
)
drive_mcp = McpToolset(
connection_params=StreamableHTTPConnectionParams(url="https://drivemcp.googleapis.com/mcp/v1"),
header_provider=auth_header_provider
)
gmail_mcp = McpToolset(
connection_params=StreamableHTTPConnectionParams(url="https://gmailmcp.googleapis.com/mcp/v1"),
header_provider=auth_header_provider
)
people_mcp = McpToolset(
connection_params=StreamableHTTPConnectionParams(url="https://people.googleapis.com/mcp/v1"),
header_provider=auth_header_provider
)
universal_search_mcp = McpToolset(
connection_params=StreamableHTTPConnectionParams(url="https://workspacemcp.googleapis.com/mcp/v1"),
header_provider=auth_header_provider
)
current_date = datetime.datetime.now().strftime("%Y-%m-%d")
root_agent = LlmAgent(
model=MODEL,
name='enterprise_ai',
instruction=f"""You are an enterprise assistant grounded securely in the user's Workspace data.
Today's current date is {current_date}. Always calculate relative dates (like 'this week' or 'upcoming meetings') using this reference.
Always use the provided MCP tools to fetch context from Calendar, Chat, Drive, Gmail, People, and search for information across multiple Google Workspace products.
If a tool returns an error indicating a timeout, inform the user that the service took too long to respond.""",
tools=[calendar_mcp, chat_mcp, drive_mcp, gmail_mcp, people_mcp, universal_search_mcp]
)
部署到 GEAP Agent Runtime
使用 ADK CLI 部署专业代码智能体:
adk deploy agent_engine \
--project=$(gcloud config get-value project) \
--region=us-central1 \
--display_name="Workspace ADK Agent" \
enterprise_ai
等待部署完成,然后从终端输出中复制生成的推理引擎资源名称(例如 projects/PROJECT_ID/locations/us-central1/reasoningEngines/ENGINE_ID)。
6. 在 Gemini Enterprise 中注册
现在,我们将自定义 ADK 智能体引入 Gemini Enterprise,以便用户可以原生方式与其对话。
创建正式版客户端 ID(Web 应用)
如需将代理部署到生产环境,您必须创建 Web 应用客户端 ID。与用于本地测试的桌面客户端不同,Web 应用客户端可实现安全的服务器端 OAuth 流程。这样,GEAP Agent Runtime 上托管的代理就可以使用指定的重定向 URI,安全地接收 Gemini Enterprise 转发的用户身份验证令牌。此设置是必需的,以便智能体在生产环境中代表用户安全地访问 Google Workspace 数据。
- 在 Google Cloud 控制台中,点击左上角的导航菜单(汉堡图标)。依次选择 Google Auth Platform > 客户端(如果看不到 Google Auth Platform,则依次选择 API 和服务 > 凭据)。点击创建客户端(或创建凭证 > OAuth 客户端 ID)。
- 选择 Web 应用作为应用类型。
- 将该文件命名为
Workspace Agent Production。 - 在已获授权的重定向 URI 部分中,添加以下 URI:
- 点击添加 URI,然后输入
https://vertexaisearch.cloud.google.com/oauth-redirect。 - 再次点击添加 URI,然后输入
https://vertexaisearch.cloud.google.com/static/oauth/oauth.html。
- 点击添加 URI,然后输入
- 选择将此客户端用于 AI 赋能的智能体,以便在 OAuth 客户端上启用
is_agentic分类标志。 - 点击创建。在“OAuth 客户端已创建”对话框中(或从客户端列表中),复制客户端 ID 和客户端密钥。在 Gemini Enterprise 中注册智能体时,您需要用到这些信息。
创建 Gemini Enterprise 应用
- 在 Google Cloud 控制台中,前往 Gemini Enterprise 页面:
- 在 Gemini Enterprise 卡片下,点击管理。
- 点击创建应用。
- 在 Gemini Enterprise 部分中,点击创建。
- 在您的应用名称字段中,输入应用的名称。应用 ID 显示在应用名称下方。
- 在贵公司或组织的外部名称字段中,输入公司或组织的名称。在本教程中,您可以使用
Cymbal Bank。 - 选择 global(全球级)作为应用的位置。
- 点击继续。
注册自定义智能体
- 打开 Gemini Enterprise 控制台:
- 选择您的活跃应用,前往代理,然后依次点击 + 添加代理 > 通过 Agent Runtime 添加自定义代理。
- 在授权部分中,点击添加授权:
- 授权名称:
workspace-adk-auth(必须与 Python 代码中的 CLIENT_AUTH_NAME 完全一致) - 客户端 ID:粘贴上面创建的正式版 Web 应用客户端 ID。
- 客户端密钥:粘贴上面创建的正式版 Web 应用客户端密钥。
- 令牌 URI:
https://oauth2.googleapis.com/token - 授权 URI:将
YOUR_CLIENT_ID替换为您在上述第 5 步中复制的客户端 ID,以构建 URI:https://accounts.google.com/o/oauth2/v2/auth?client_id=YOUR_CLIENT_ID&redirect_uri=https%3A%2F%2Fvertexaisearch.cloud.google.com%2Fstatic%2Foauth%2Foauth.html&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.events%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.calendars%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.readonly%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fchat.spaces%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fchat.messages%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.readonly%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.file%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.readonly%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.compose%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdirectory.readonly%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcontacts.readonly%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform&include_granted_scopes=true&response_type=code&access_type=offline&prompt=consent
- 授权名称:
- 点击完成,然后点击下一步。
- 在配置部分中:
- 代理名称:
Workspace Pro Agent - 说明:
Use this agent to answer questions about your Google Workspace data, including Gmail, Google Drive, Google Calendar, Google Chat, and Contacts. It can find files, summarize emails, check your schedule, and look up contact information. - Agent Runtime 推理引擎:粘贴您从
adk deploy输出中复制的引擎资源名称。
- 代理名称:
- 点击创建。
在 Gemini Enterprise 中试用该智能体
您可以使用 Google Cloud 控制台预览版(对开发者而言最快)或 Gemini Enterprise Web 应用(最终用户体验)与智能体互动。
选项 1:Google Cloud 控制台预览
- 在 Google Cloud 控制台中,前往 Gemini Enterprise 页面:
- 在导航菜单中,点击应用,然后选择您刚刚创建的应用。
- 点击预览或点击右上角的打开预览。
- 在搜索栏中,输入以下查询:
Search for files in Drive related to 'Project Milestone', summarize them, and tell me if I have any meetings with the project owner today. - 按 Enter 键提交查询,并直接在控制台中查看结果。
选项 2:Gemini Enterprise Web 应用
- 打开 Gemini Enterprise Web 应用界面。
- 依次前往菜单 ☰ > 代理,然后在来自贵组织下选择 Workspace Pro 代理。
- 输入与 Google Cloud 控制台预览选项中相同的查询。
- 当系统提示您完成 OAuth 用户同意流程时,点击授权。
- 智能体将使用 MCP 协议在多项服务之间无缝执行任务!
7. 清理
为避免产生不必要的费用,请清理您的资源:
控制台选项
前往 API 和服务信息中心,选择您启用的 MCP 服务(例如 Calendar MCP、Gmail MCP),然后点击停用 API。删除 Google Auth Platform > 客户端下的 OAuth 客户端 ID,并从 Gemini Enterprise 控制台中删除推理引擎部署。
CLI 选项
执行以下终端命令以停用 MCP 服务:
# Disable Workspace MCP services
gcloud services disable calendarmcp.googleapis.com \
chatmcp.googleapis.com \
drivemcp.googleapis.com \
gmailmcp.googleapis.com \
workspacemcp.googleapis.com
8. 恭喜
恭喜!您已成功构建、测试和部署一个直接连接到官方 Google Workspace MCP 服务器的专业代码 ADK AI 智能体。
您学到的内容
- 如何在 Google Cloud 中启用 Google Workspace MCP 服务。
- 如何使用静态标头处理 OAuth 凭据以进行本地 ADK 测试。
- 如何使用
header_provider为生产代理实现动态令牌注入。 - 如何将 ADK 智能体部署到 GEAP Agent Runtime 并在 Gemini Enterprise 中注册。