1. บทนำ
ใน Codelab นี้ คุณจะได้เรียนรู้วิธีสร้าง AI Agent ที่ใช้โค้ดมากโดยใช้ Agent Development Kit (ADK) ซึ่งเชื่อมต่อกับ เซิร์ฟเวอร์ Google Workspace MCP อย่างเป็นทางการโดยตรง
Model Context Protocol (MCP) เป็นมาตรฐานแบบเปิดที่ช่วยให้โมเดล AI ใช้เครื่องมือที่เซิร์ฟเวอร์ระยะไกลจัดหาให้ได้อย่างปลอดภัย ADK เป็นเฟรมเวิร์กที่ใช้โค้ดมากของ Google สำหรับสร้าง Agent แบบอัตโนมัติ การรวมเฟรมเวิร์กทั้ง 2 เข้าด้วยกันจะช่วยให้คุณสร้าง Agent ที่ปรับแต่งได้สูงโดยอิงตามข้อมูล Gmail, Google ไดรฟ์, Google ปฏิทิน, Google Chat และข้อมูลผู้คน
โปรดดูเอกสารประกอบฉบับเต็มเกี่ยวกับเครื่องมือและการกำหนดค่าที่มีให้ที่หัวข้อกำหนดค่าเซิร์ฟเวอร์ Google Workspace MCP
สิ่งที่คุณจะได้ทำ
- เปิดใช้บริการ Google Workspace MCP ในโปรเจ็กต์ที่อยู่ในระบบคลาวด์ของ Google
- กำหนดค่าคำยินยอม OAuth และสร้างข้อมูลเข้าสู่ระบบสำหรับการทดสอบในเครื่องและการติดตั้งใช้งานจริง
- สร้าง Agent ADK ในเครื่องที่เชื่อมต่อกับเซิร์ฟเวอร์ Workspace MCP ทั้ง 5 รายการโดยใช้โทเค็นแบบคงที่
- สร้างและทำให้ Agent ADK ที่พร้อมใช้งานจริงกับ Gemini Enterprise Agent Platform (GEAP) Agent Runtime ซึ่งใช้การแทรกโทเค็นแบบไดนามิก
- ลงทะเบียนและทดสอบ Agent ที่กำหนดเองภายใน 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 เฉพาะ
ตัวเลือกคอนโซล
คลิกปุ่มต่อไปนี้เพื่อเปิดใช้ API โดยใช้เว็บเบราว์เซอร์
ตัวเลือก 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 คุณต้องกำหนดค่าแอป Chat ในโปรเจ็กต์ที่อยู่ในระบบคลาวด์ของ Google
- ในคอนโซล 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 รายการ ได้แก่ รหัสหนึ่งสำหรับการพัฒนาในเครื่อง และอีกรหัสหนึ่งสำหรับ Agent ที่ติดตั้งใช้งาน
ตั้งค่าหน้าจอขอความยินยอม OAuth
- ในคอนโซล Google Cloud ให้คลิกเมนูการนำทาง (ไอคอนแฮมเบอร์เกอร์) ที่มุมซ้ายบน เลือก Google Auth Platform > การสร้างแบรนด์ (หรือ API และบริการ > หน้าจอขอคำยินยอม OAuth หากไม่เห็น Google Auth Platform)
- กำหนดค่าข้อมูลแอป:
- ชื่อแอป:
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 - คลิกเพิ่มลงในตาราง แล้วคลิกอัปเดต และสุดท้ายคลิกบันทึก
สร้างรหัสไคลเอ็นต์สำหรับการพัฒนาในเครื่อง (แอปบนเดสก์ท็อป)
- ในคอนโซล Google Cloud ให้ไปที่ Google Auth Platform > ไคลเอ็นต์ (หรือ API และบริการ > ข้อมูลเข้าสู่ระบบ) คลิกสร้างข้อมูลเข้าสู่ระบบ (หรือสร้างไคลเอ็นต์) แล้วเลือกรหัสไคลเอ็นต์ OAuth
- เลือกแอปบนเดสก์ท็อป เป็นประเภทแอปพลิเคชัน
- ตั้งชื่อเป็น
Workspace Agent Local - คลิกสร้าง แล้วดาวน์โหลดไฟล์ JSON บันทึกไฟล์ในเครื่องเป็น
client_secret.json
4. การพัฒนาและการทดสอบ Agent
ส่วนนี้จะอธิบายวิธีสร้างสภาพแวดล้อมของเอเจนต์ เราจะใช้แนวทางโทเค็นแบบคงที่สำหรับการทดสอบ โดยดึงโทเค็น OAuth โดยใช้ gcloud แล้วส่งโทเค็นไปยัง McpToolset ของ ADK คุณสามารถทำตามขั้นตอนเหล่านี้โดยใช้เครื่องในเครื่อง หรือ Google Cloud Shell
เลือกสภาพแวดล้อมเป็น เครื่องในเครื่อง หรือ Google Cloud Shell เพื่อตั้งค่าสภาพแวดล้อมในการพัฒนาซอฟต์แวร์ ทั้ง 2 วิธีจะใช้สคริปต์ Python ที่แชร์สำหรับการตรวจสอบสิทธิ์เพื่อให้มั่นใจถึงความสอดคล้องในทุกแพลตฟอร์ม
1. ตั้งค่าไดเรกทอรีสภาพแวดล้อม
เรียกใช้คำสั่งต่อไปนี้ในเทอร์มินัลเพื่อสร้างไดเรกทอรีโปรเจ็กต์และติดตั้งแพ็กเกจที่จำเป็น
- สำหรับ Google Cloud Shell: ขั้นแรก ให้คลิกไอคอนเปิดใช้งาน Cloud Shell (
>_) ในแถบเครื่องมือด้านขวาบนของคอนโซล Google Cloud - สำหรับเครื่องในเครื่อง: เปิดเทอร์มินัลมาตรฐาน
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)
เราใช้สคริปต์ Python ที่กำหนดเองซึ่งขับเคลื่อนโดยไลบรารีการตรวจสอบสิทธิ์อย่างเป็นทางการของ Google เพื่อจัดการการตรวจสอบสิทธิ์อย่างสม่ำเสมอและหลีกเลี่ยงปัญหาการกำหนดเส้นทาง CLI ที่เฉพาะเจาะจงกับสภาพแวดล้อม สคริปต์นี้จะจัดการขั้นตอน OAuth, บันทึกข้อมูลรับรองเริ่มต้นของแอปพลิเคชัน (ADC) ในเครื่อง และสร้างไฟล์ .env ที่จำเป็น
สร้างไฟล์ชื่อ auth.py ในไดเรกทอรี gws-adk-agent แล้วเพิ่มโค้ดต่อไปนี้
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
สร้างโค้ด Agent
โค้ด Agent จะยังคงเหมือนเดิมไม่ว่าคุณจะเลือกสภาพแวดล้อมใดในขั้นตอนก่อนหน้า สร้างไฟล์ชื่อ agent.py ในไดเรกทอรีย่อย workspace_agent ที่สร้างไว้ก่อนหน้า แล้วเพิ่มโค้ดต่อไปนี้ สคริปต์นี้ใช้ข้อมูลรับรองเริ่มต้นของแอปพลิเคชัน (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]
)
เรียกใช้และทดสอบ Agent
คุณสามารถโต้ตอบกับเอเจนต์ของคุณได้โดยใช้อินเทอร์เฟซผู้ใช้เว็บ แบบอินเทอร์แอกทีฟหรือภายใน เทอร์มินัล/Shell โดยตรง
ตัวเลือกที่ 1: อินเทอร์เฟซผู้ใช้เว็บแบบอินเทอร์แอกทีฟ
หากคุณใช้เครื่องในเครื่อง ให้ทำดังนี้
- จากไดเรกทอรีรากของโปรเจ็กต์
gws-adk-agentให้เริ่มอินเทอร์เฟซเว็บของ ADK โดยใช้คำสั่งต่อไปนี้adk web - เปิด
http://localhost:8000ในเบราว์เซอร์เพื่อแชทกับ Agent
หากคุณอยู่ใน 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
คุณจะเข้าสู่เซสชันการแชทแบบอินเทอร์แอกทีฟในเชลล์โดยตรง
Running agent gws_adk_agent, type exit to exit.
[user]:
ลองเขียนพรอมต์สำหรับ Agent
ไม่ว่าคุณจะเลือกอินเทอร์เฟซใด ให้ลองทดสอบ Agent ด้วยคําค้นหาที่ใช้ประโยชน์จากเครื่องมือ Workspace MCP
What are my upcoming meetings this week?
Summarize the last 3 unread emails in my Gmail.
5. การติดตั้งใช้งานจริง
หากต้องการติดตั้งใช้งาน Agent จริง เราจะใช้โทเค็นในเครื่องที่ฮาร์ดโค้ดไม่ได้ แต่เราจะใช้ header_provider ของ ADK เพื่อดึงโทเค็นเพื่อการเข้าถึง OAuth ที่แพลตฟอร์ม Gemini Enterprise แทรกแบบไดนามิกเมื่อผู้ใช้โต้ตอบกับ Agent
สร้างโค้ด Agent สำหรับการใช้งานจริง
สร้างแพ็กเกจไดเรกทอรีชื่อ 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
ติดตั้งใช้งาน Agent ที่ใช้โค้ดมากโดยใช้ ADK CLI โดยใช้คำสั่งต่อไปนี้
adk deploy agent_engine \
--project=$(gcloud config get-value project) \
--region=us-central1 \
--display_name="Workspace ADK Agent" \
enterprise_ai
รอให้การติดตั้งใช้งานเสร็จสิ้น แล้วคัดลอกชื่อทรัพยากรของ Reasoning Engine ที่สร้างขึ้นจากเอาต์พุตของเทอร์มินัล (เช่น projects/PROJECT_ID/locations/us-central1/reasoningEngines/ENGINE_ID)
6. ลงทะเบียนใน Gemini Enterprise
ตอนนี้เราจะนำ Agent ADK ที่กำหนดเองไปไว้ใน Gemini Enterprise เพื่อให้ผู้ใช้แชทกับ Agent ได้โดยตรง
สร้างรหัสไคลเอ็นต์สำหรับการใช้งานจริง (เว็บแอปพลิเคชัน)
หากต้องการติดตั้งใช้งาน Agent จริง คุณต้องสร้างรหัสไคลเอ็นต์สำหรับเว็บแอปพลิเคชัน ไคลเอ็นต์สำหรับเว็บแอปพลิเคชันจะเปิดใช้ขั้นตอน OAuth ฝั่งเซิร์ฟเวอร์ที่ปลอดภัย ซึ่งแตกต่างจากไคลเอ็นต์บนเดสก์ท็อปที่ใช้สำหรับการทดสอบในเครื่อง การดำเนินการนี้ช่วยให้ Agent ที่โฮสต์ใน GEAP Agent Runtime รับโทเค็นการตรวจสอบสิทธิ์ของผู้ใช้ที่ Gemini Enterprise ส่งต่อมาได้อย่างปลอดภัยโดยใช้ URI การเปลี่ยนเส้นทางที่ระบุ การตั้งค่านี้จำเป็นเพื่อให้ Agent เข้าถึงข้อมูล Google Workspace ในนามของผู้ใช้ในสภาพแวดล้อมการใช้งานจริงได้อย่างปลอดภัย
- ในคอนโซล Google Cloud ให้คลิกเมนูการนำทาง (ไอคอนแฮมเบอร์เกอร์) ที่มุมซ้ายบน เลือก Google Auth Platform > ไคลเอ็นต์ (หรือ API และบริการ > ข้อมูลเข้าสู่ระบบ หากไม่เห็น Google Auth Platform) คลิกสร้างข้อมูลเข้าสู่ระบบ (หรือสร้างไคลเอ็นต์) แล้วเลือกรหัสไคลเอ็นต์ OAuth
- เลือกเว็บแอปพลิเคชัน เป็นประเภทแอปพลิเคชัน
- ตั้งชื่อเป็น
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 แล้ว" (หรือจากรายการไคลเอ็นต์) ให้คัดลอกรหัสไคลเอ็นต์ และรหัสลับไคลเอ็นต์ คุณจะต้องใช้ข้อมูลเหล่านี้เมื่อลงทะเบียน Agent ใน Gemini Enterprise
สร้างแอป Gemini Enterprise
- ในคอนโซล Google Cloud ให้ไปที่หน้า Gemini Enterprise
- คลิกจัดการ ในการ์ด Gemini Enterprise
- คลิกสร้างแอป
- ในส่วน Gemini Enterprise ให้คลิกสร้าง
- ป้อนชื่อแอปในช่องชื่อแอป รหัสแอปจะปรากฏใต้ชื่อแอป
- ป้อนชื่อบริษัทหรือองค์กรในช่องชื่อภายนอกของบริษัทหรือองค์กร สำหรับบทแนะนำนี้ คุณสามารถใช้
Cymbal Bank - เลือกทั่วโลก (Global) เป็นสถานที่ตั้งของแอป
- คลิกต่อไป
ลงทะเบียน Agent ที่กำหนดเอง
- เปิดคอนโซล Gemini Enterprise โดยใช้คำสั่งต่อไปนี้
- เลือกแอปที่ใช้งานอยู่ ไปที่ Agents แล้วคลิก + Add agent > Add Custom agent via Agent Runtime
- ในส่วนการให้สิทธิ์ ให้คลิกเพิ่มการให้สิทธิ์:
- ชื่อการให้สิทธิ์:
workspace-adk-auth(ต้องตรงกับ CLIENT_AUTH_NAME ในโค้ด Python ทุกประการ) - รหัสไคลเอ็นต์: วางรหัสไคลเอ็นต์ของ เว็บแอปพลิเคชันสำหรับการใช้งานจริง ที่สร้างไว้ข้างต้น
- รหัสลับไคลเอ็นต์: วางรหัสลับไคลเอ็นต์ของ เว็บแอปพลิเคชันสำหรับการใช้งานจริง ที่สร้างไว้ข้างต้น
- URI ของโทเค็น:
https://oauth2.googleapis.com/token - URI การให้สิทธิ์: สร้าง URI โดยแทนที่
YOUR_CLIENT_IDด้วยรหัสไคลเอ็นต์ ที่คัดลอกไว้ในขั้นตอนที่ 5 ด้านบน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
- ชื่อการให้สิทธิ์:
- คลิกเสร็จสิ้น แล้วคลิกถัดไป
- ในส่วนการกำหนดค่า ให้ป้อนข้อมูลต่อไปนี้
- ชื่อ Agent:
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. - Reasoning Engine ของ Agent Runtime: วางชื่อทรัพยากรของ Engine ที่คัดลอกจากเอาต์พุต
adk deploy
- ชื่อ Agent:
- คลิกสร้าง
ลองใช้ Agent ใน Gemini Enterprise
คุณสามารถโต้ตอบกับ Agent ได้โดยใช้คอนโซล Google Cloud Preview (เร็วที่สุดสำหรับนักพัฒนาแอป) หรือเว็บแอป 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
- ไปที่เมนู ☰ > Agents แล้วเลือก Workspace Pro Agent ในส่วน จากองค์กรของคุณ
- พิมพ์คำค้นหาเดียวกันกับในตัวเลือกการแสดงตัวอย่างคอนโซล Google Cloud
- คลิกให้สิทธิ์ เมื่อได้รับข้อความแจ้งให้ดำเนินการตามขั้นตอนความยินยอมของผู้ใช้ OAuth
- Agent จะทำงานต่างๆ ได้อย่างราบรื่นในหลายบริการโดยใช้โปรโตคอล MCP
7. ล้างข้อมูล
ล้างข้อมูลทรัพยากรเพื่อหลีกเลี่ยงค่าใช้จ่ายที่ไม่จำเป็นโดยทำดังนี้
ตัวเลือกคอนโซล
ไปที่แดชบอร์ด API และบริการ เลือกบริการ MCP ที่เปิดใช้ (เช่น Calendar MCP, Gmail MCP) แล้วคลิกปิดใช้ API ลบรหัสไคลเอ็นต์ OAuth ในส่วน Google Auth Platform > ไคลเอ็นต์ และลบการติดตั้งใช้งาน Reasoning Engine จาก คอนโซล Gemini Enterprise
ตัวเลือก CLI
เรียกใช้คำสั่งต่อไปนี้ในเทอร์มินัลเพื่อปิดใช้บริการ MCP
# Disable Workspace MCP services
gcloud services disable calendarmcp.googleapis.com \
chatmcp.googleapis.com \
drivemcp.googleapis.com \
gmailmcp.googleapis.com
8. ขอแสดงความยินดี
ขอแสดงความยินดี คุณสร้าง ทดสอบ และติดตั้งใช้งาน AI Agent ADK ที่ใช้โค้ดมากซึ่งเชื่อมต่อกับเซิร์ฟเวอร์ Google Workspace MCP อย่างเป็นทางการโดยตรงได้สำเร็จแล้ว
สิ่งที่คุณได้เรียนรู้
- วิธีเปิดใช้บริการ Google Workspace MCP ใน Google Cloud
- วิธีจัดการข้อมูลเข้าสู่ระบบ OAuth สำหรับการทดสอบ ADK ในเครื่องโดยใช้ส่วนหัวแบบคงที่
- วิธีใช้การแทรกโทเค็นแบบไดนามิกโดยใช้
header_providerสำหรับ Agent ที่ใช้งานจริง - วิธีติดตั้งใช้งาน Agent ADK กับ GEAP Agent Runtime และลงทะเบียน Agent ใน Gemini Enterprise