1. はじめに
この Codelab では、Agent Development Kit(ADK)を使用して、公式の Google Workspace MCP サーバーに直接接続するプロコード AI エージェントを構築する方法を学びます。
Model Context Protocol(MCP)は、AI モデルがリモート サーバーから提供されるツールを安全に使用できるようにするオープン スタンダードです。ADK は、自律型エージェントを構築するための Google のプロコード フレームワークです。これらを組み合わせることで、Gmail、Google ドライブ、Google カレンダー、Google Chat、連絡先のデータに基づいて、高度にカスタマイズされたエージェントを作成できます。
使用可能なツールと構成に関する詳細なドキュメントについては、Google Workspace MCP サーバーを構成するをご覧ください。
演習内容
- Google Cloud プロジェクトで Google Workspace MCP サービスを有効にします。
- OAuth 同意を構成し、ローカルテストと本番環境へのデプロイの両方の認証情報を作成します。
- 静的トークンを使用して Google Workspace MCP サーバーに接続するローカル ADK エージェントを構築する。
- 動的トークン インジェクションを使用するプロダクション レディな 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 Console で、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 用アプリを構成する必要があります。
- Google Cloud コンソールで Google Chat API を検索し、[Google Chat API] > [管理] > [構成] をクリックします。
- Chat 用アプリを設定します。
- アプリ名:
ADK Workspace Agent - アバターの URL:
https://developers.google.com/chat/images/quickstart-app-avatar.png - 説明:
MCP server connection for ADK Agent - [機能] で、[インタラクティブ機能を有効にする] をオフにします。
- [ログ] で、[エラーを Logging にロギングする] を選択します。
- アプリ名:
- [保存] をクリックします。
3. OAuth の同意とクライアントを構成する
Google Workspace MCP サーバーは、安全な認証に OAuth 2.0 を使用します。OAuth 同意画面を構成し、2 つの個別のクライアント ID(ローカル開発用とデプロイされたエージェント用)を作成する必要があります。
OAuth 同意画面を設定する
- Google Cloud コンソールの左上にあるナビゲーション メニュー(ハンバーガー アイコン)をクリックします。[Google Auth Platform] > [ブランディング] を選択します(Google Auth Platform が表示されない場合は、[API とサービス] > [OAuth 同意画面] を選択します)。
- [App Information] を構成します。
- アプリ名:
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 - [Add to Table]、[Update]、[Save] の順にクリックします。
ローカル開発用のクライアント 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]
)
エージェントを実行してテストする
エージェントを操作するには、インタラクティブなウェブ UI を使用するか、ターミナル / シェル内で直接操作します。
オプション 1: インタラクティブなウェブ UI
ローカルマシンを使用している場合:
gws-adk-agentプロジェクトのルート ディレクトリから、ADK ウェブ インターフェースを起動します。adk web- ブラウザで
http://localhost:8000を開き、エージェントとチャットします。
Google Cloud Shell を使用している場合:
gws-adk-agentプロジェクトのルート ディレクトリから、ポート 8080 を明示的に適用して ADK ウェブ インターフェースを起動します。adk web --port 8080 --allow_origins=*- Cloud Shell ツールバーの右上にある [ウェブでプレビュー] ボタンをクリックし、[ポート 8080 でプレビュー] を選択して、新しいタブでインターフェースを開きます。
オプション 2: ターミナル CLI モード(代替)
ターミナルで作業を続けたい場合や、ウェブブラウザのプレビューを設定したくない場合は、ADK のネイティブなインタラクティブ REPL チャットモードを使用できます。
gws-adk-agent プロジェクトのルート ディレクトリから、次のコマンドを実行します(このコマンドは、ローカルマシンと Google Cloud Shell の両方で同じように動作します)。
adk run workspace_agent
シェルで直接インタラクティブなチャット セッションを開始します。
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 を作成する(ウェブ アプリケーション)
エージェントを本番環境にデプロイするには、ウェブ アプリケーションのクライアント ID を作成する必要があります。ローカルテストに使用されるデスクトップ クライアントとは異なり、ウェブ アプリケーション クライアントでは、安全なサーバーサイド OAuth フローが可能です。これにより、GEAP Agent Runtime でホストされているエージェントは、指定されたリダイレクト URI を使用して、Gemini Enterprise から転送されたユーザーの認証トークンを安全に受信できます。この設定は、エージェントが本番環境でユーザーに代わって Google Workspace データに安全にアクセスするために必要です。
- Google Cloud コンソールの左上にあるナビゲーション メニュー(ハンバーガー アイコン)をクリックします。[Google Auth Platform] > [クライアント] を選択します(Google Auth Platform が表示されない場合は、[API とサービス] > [認証情報] を選択します)。[クライアントを作成](または [認証情報を作成] > [OAuth クライアント ID])をクリックします。
- アプリケーションの種類として [ウェブ アプリケーション] を選択します。
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 (Global)] を選択します。
- [続行] をクリックします。
カスタム エージェントを登録する
- Gemini Enterprise コンソールを開きます。
- アクティブなアプリを選択し、[エージェント] に移動して、[+ エージェントを追加] > [Agent Runtime によるカスタム エージェントを追加] をクリックします。
- [承認] セクションで、[承認を追加] をクリックします。
- 認可名:
workspace-adk-auth(Python コードの CLIENT_AUTH_NAME と完全に一致している必要があります) - クライアント ID: 上記で作成した本番環境ウェブ アプリケーションのクライアント ID を貼り付けます。
- クライアント シークレット: 上記で作成した本番環境ウェブ アプリケーションのクライアント シークレットを貼り付けます。
- トークン URI:
https://oauth2.googleapis.com/token - 認可 URI: 上記の手順 5 でコピーしたクライアント ID で
YOUR_CLIENT_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
- 認可名:
- [Done]、[Next] の順にクリックします。
- [構成] セクションで、次の操作を行います。
- エージェント名:
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 ウェブアプリ(エンドユーザー エクスペリエンス)を使用します。
オプション 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 ウェブアプリ
- Gemini Enterprise ウェブアプリのインターフェースを開きます。
- メニュー アイコン ☰ > [エージェント] に移動し、[組織から] で [Workspace Pro Agent] を選択します。
- 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 サービスを有効にする方法。
- 静的ヘッダーを使用してローカル ADK テストの OAuth 認証情報を処理する方法。
- 本番環境エージェントで
header_providerを使用して動的トークン インジェクションを実装する方法。 - ADK エージェントを GEAP Agent Runtime にデプロイし、Gemini Enterprise に登録する方法。