1. はじめに
この Codelab では、公式の Google Workspace MCP サーバー に直接接続する Agent Development Kit(ADK) を使用して、プロコード AI エージェントを構築する方法について説明します。
Model Context Protocol(MCP)は、AI モデルがリモートサーバーから提供されるツールを安全に使用できるようにするオープン スタンダードです。ADK は、自律型エージェントを構築するための Google のプロコード フレームワークです。これらを組み合わせることで、Gmail、Google ドライブ、Google カレンダー、Google Chat、連絡先のデータに基づいた高度にカスタマイズされたエージェントを作成できます。
使用可能なツールと構成の詳細なドキュメントについては、Google Workspace MCP サーバーを構成するをご覧ください。
演習内容
- Google Cloud プロジェクトで Google Workspace MCP サービス を有効にします。
- OAuth 同意を構成し、ローカルテストと本番環境デプロイの両方の認証情報を作成します。
- 静的トークンを使用して 5 つの 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 コンソール で、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
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 同意画面])を選択します。
- アプリ情報を構成します。
- アプリ名:
Workspace ADK Agent - ユーザー サポートメール: メールアドレスを選択します。
- アプリ名:
- [オーディエンス] を構成します。[**内部**] を選択します。
- [連絡先情報] を構成します。メールアドレスを入力して、[作成] をクリックします。
- [データアクセス] > [スコープの追加または削除] に移動します。[スコープの手動追加] で、次のスコープを追加して、5 つのサービスすべてへのアクセスを許可します。
https://www.googleapis.com/auth/calendar.calendarlist.readonly https://www.googleapis.com/auth/calendar.events https://www.googleapis.com/auth/calendar.calendars 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/gmail.send 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 Cloud コンソールで、[Google Auth Platform] > [クライアント](または [API とサービス] > [認証情報])に移動します。[認証情報を作成](または [クライアントを作成])をクリックし、[OAuth クライアント ID] を選択します。
- アプリケーションの種類として [デスクトップ アプリ] を選択します。
Workspace Agent Localという名前を付けます。- [作成] をクリックして 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 5 GWS 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
)
current_date = datetime.datetime.now().strftime("%Y-%m-%d")
# Define the agent and attach all 5 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, and Contacts.
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]
)
エージェントを実行してテストする
エージェントを操作するには、インタラクティブなウェブ 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
)
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, and People.
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]
)
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 を追加] をクリックして、
- [作成] をクリックします。[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.readonly%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.calendars%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.events%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.send%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.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%2Fdirectory.readonly&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 ウェブアプリ (エンドユーザー エクスペリエンス)を使用します。
オプション 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 サービス(カレンダー 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
8. 完了
おめでとうございます!公式の Google Workspace MCP サーバーに直接接続するプロコード ADK AI エージェントを構築、テスト、デプロイできました。
学習した内容
- Google Cloud で Google Workspace MCP サービスを有効にする方法。
- 静的ヘッダーを使用してローカル ADK テストの OAuth 認証情報を処理する方法。
- 本番環境エージェントに
header_providerを使用して動的トークン挿入を実装する方法。 - ADK エージェントを GEAP Agent Runtime にデプロイし、Gemini Enterprise に登録する方法。