สร้าง Agent AI ของ Google Workspace ด้วย ADK และ MCP

1. บทนำ

ใน Codelab นี้ คุณจะได้เรียนรู้วิธีสร้าง AI Agent แบบ Pro-Code โดยใช้ Agent Development Kit (ADK) ที่เชื่อมต่อโดยตรงกับเซิร์ฟเวอร์ MCP ของ Google Workspace อย่างเป็นทางการ

Model Context Protocol (MCP) เป็นมาตรฐานแบบเปิดที่ช่วยให้โมเดล AI ใช้เครื่องมือที่เซิร์ฟเวอร์ระยะไกลจัดเตรียมไว้ได้อย่างปลอดภัย ADK เป็นเฟรมเวิร์ก Pro-Code ของ Google สำหรับสร้าง Agent แบบอัตโนมัติ เมื่อรวมเข้าด้วยกัน คุณจะสร้าง Agent ที่ปรับแต่งได้สูงซึ่งอิงตามข้อมูลใน Gmail, Google ไดรฟ์, Google ปฏิทิน, Google Chat และ People ได้

โปรดดูเอกสารประกอบฉบับสมบูรณ์เกี่ยวกับเครื่องมือและการกำหนดค่าที่พร้อมใช้งานที่หัวข้อกำหนดค่าเซิร์ฟเวอร์ MCP ของ Google Workspace

สิ่งที่คุณจะทำ

  • เปิดใช้บริการ MCP ของ Google Workspace ในโปรเจ็กต์ที่อยู่ในระบบคลาวด์ของ Google
  • กำหนดค่าความยินยอมของ OAuth และสร้างข้อมูลเข้าสู่ระบบสำหรับการทดสอบในเครื่องและการทำให้ใช้งานได้จริง
  • สร้าง Agent ประเภท ADK ในเครื่องที่เชื่อมต่อกับเซิร์ฟเวอร์ MCP ของ Google Workspace โดยใช้โทเค็นแบบคงที่
  • สร้างและติดตั้งใช้งาน ADK Agent ที่พร้อมใช้งานจริงใน รันไทม์ของ Agent ของ Gemini Enterprise Agent Platform (GEAP) ซึ่งใช้การแทรกโทเค็นแบบไดนามิก
  • ลงทะเบียนและทดสอบ 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

หากต้องการใช้เซิร์ฟเวอร์ MCP ของ Google Workspace คุณต้องเปิดใช้ทั้ง 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

หากต้องการใช้เซิร์ฟเวอร์ MCP ของ Google Chat คุณต้องกำหนดค่าแอปใน Chat ในโปรเจ็กต์ที่อยู่ในระบบคลาวด์ของ Google

  1. ในคอนโซล Google Cloud ให้ค้นหา Google Chat API แล้วคลิก Google Chat API > จัดการ > การกำหนดค่า
  2. ตั้งค่าแอป Chat ดังนี้
    • ชื่อแอป: ADK Workspace Agent
    • URL ของรูปโปรไฟล์: https://developers.google.com/chat/images/quickstart-app-avatar.png
    • คำอธิบาย: MCP server connection for ADK Agent
    • ในส่วนฟังก์ชันการทำงาน ให้ปิดเปิดใช้ฟีเจอร์แบบอินเทอร์แอกทีฟ
    • ในส่วนบันทึก ให้เลือกบันทึกข้อผิดพลาดไปยัง Logging
  3. คลิกบันทึก

3. กำหนดค่าความยินยอมและไคลเอ็นต์ OAuth

เซิร์ฟเวอร์ MCP ของ Google Workspace ใช้ OAuth 2.0 เพื่อการตรวจสอบสิทธิ์ที่ปลอดภัย คุณต้องกำหนดค่าหน้าจอขอความยินยอม OAuth และสร้างรหัสไคลเอ็นต์แยกกัน 2 รายการ โดยรายการหนึ่งสำหรับการพัฒนาในเครื่อง และอีกรายการหนึ่งสำหรับ Agent ที่ติดตั้งใช้งาน

  1. ในคอนโซล Google Cloud ให้คลิกเมนูการนำทาง (ไอคอนแฮมเบอร์เกอร์) ที่มุมซ้ายบน เลือกแพลตฟอร์มการตรวจสอบสิทธิ์ของ Google > การสร้างแบรนด์ (หรือ API และบริการ > หน้าจอขอความยินยอม OAuth หากไม่เห็นแพลตฟอร์มการตรวจสอบสิทธิ์ของ Google)
  2. กำหนดค่าข้อมูลแอป:
    • ชื่อแอป: Workspace ADK Agent
    • อีเมลสนับสนุนสำหรับผู้ใช้: เลือกอีเมลของคุณ
  3. กำหนดค่ากลุ่มเป้าหมาย: เลือกภายใน
  4. กำหนดค่าข้อมูลติดต่อ: ป้อนอีเมล แล้วคลิกสร้าง
  5. ไปที่การเข้าถึงข้อมูล > เพิ่มหรือนำขอบเขตออก ในส่วนเพิ่มขอบเขตด้วยตนเอง ให้เพิ่มขอบเขตต่อไปนี้เพื่อมอบสิทธิ์เข้าถึงบริการที่จำเป็น
    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
    
  6. คลิกเพิ่มลงในตาราง แล้วคลิกอัปเดต จากนั้นคลิกบันทึก

สร้างรหัสไคลเอ็นต์สำหรับการพัฒนาในเครื่อง (แอปบนเดสก์ท็อป)

เมื่อกำหนดค่าไคลเอ็นต์ OAuth 2.0 สำหรับเซิร์ฟเวอร์ MCP ของ Google Workspace คุณต้องเปิดใช้การตั้งค่าการแยกประเภท Agentic (is_agentic) โดยเลือกใช้ไคลเอ็นต์นี้สำหรับ Agent ที่ทำงานด้วยระบบ AI ไคลเอ็นต์ OAuth ที่ไม่ได้เปิดใช้การตั้งค่านี้จะถูกบล็อกไม่ให้เรียกใช้ปลายทาง MCP ของ Google Workspace

  1. ในคอนโซล Google Cloud ให้ไปที่ Google Auth Platform > ไคลเอ็นต์ (หรือ API และบริการ > ข้อมูลเข้าสู่ระบบ) คลิกสร้างไคลเอ็นต์ (หรือสร้างข้อมูลเข้าสู่ระบบ > รหัสไคลเอ็นต์ OAuth)
  2. เลือกแอปบนเดสก์ท็อปเป็นประเภทแอปพลิเคชัน
  3. ตั้งชื่อว่า Workspace Agent Local
  4. เลือกใช้ไคลเอ็นต์นี้สำหรับ Agent ที่ทำงานด้วยระบบ AI เพื่อเปิดใช้แฟล็กการแยกประเภท is_agentic ในไคลเอ็นต์ OAuth
  5. คลิกสร้าง แล้วดาวน์โหลดไฟล์ JSON บันทึกไว้ในเครื่องเป็น client_secret.json

4. การพัฒนาและการทดสอบ Agent

ส่วนนี้จะอธิบายวิธีสร้างสภาพแวดล้อมของ 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.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 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]
)

เรียกใช้และทดสอบ Agent

คุณสามารถโต้ตอบกับ Agent โดยใช้ Web UI แบบอินเทอร์แอกทีฟหรือภายในเทอร์มินัล/เชลล์โดยตรง

ตัวเลือกที่ 1: UI บนเว็บแบบอินเทอร์แอกทีฟ

หากใช้เครื่องในพื้นที่ ให้ทำดังนี้

  1. จากไดเรกทอรีรากของโปรเจ็กต์ gws-adk-agent ให้เริ่มอินเทอร์เฟซเว็บของ ADK โดยทำดังนี้
    adk web
    
  2. เปิด http://localhost:8000 ในเบราว์เซอร์เพื่อแชทกับตัวแทน

หากคุณอยู่ใน Google Cloud Shell ให้ทำดังนี้

  1. จากไดเรกทอรีรากของโปรเจ็กต์ gws-adk-agent ให้เริ่มอินเทอร์เฟซเว็บ ADK ที่บังคับใช้พอร์ต 8080 อย่างชัดเจน โดยทำดังนี้
    adk web --port 8080 --allow_origins=*
    
  2. คลิกปุ่มตัวอย่างเว็บที่ด้านขวาบนของแถบเครื่องมือ 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]:

ลองป้อนพรอมต์ให้ Agent

ไม่ว่าคุณจะเลือกอินเทอร์เฟซใด ให้ลองทดสอบ Agent ด้วยคำถามที่ใช้ประโยชน์จากเครื่องมือ MCP ของ Workspace ดังนี้

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

สร้างรหัสตัวแทนเวอร์ชันที่ใช้งานจริง

สร้างแพ็กเกจไดเรกทอรีชื่อ 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

ติดตั้งใช้งาน Agent แบบ Pro-Code โดยใช้ 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 ที่โฮสต์ในรันไทม์ของ Agent ของ GEAP รับโทเค็นการตรวจสอบสิทธิ์ของผู้ใช้ที่ Gemini Enterprise ส่งต่อได้อย่างปลอดภัยโดยใช้ URI การเปลี่ยนเส้นทางที่ระบุ การตั้งค่านี้จำเป็นเพื่อให้ Agent เข้าถึงข้อมูล Google Workspace ในนามของผู้ใช้ในสภาพแวดล้อมฮาร์ดแวร์และซอฟต์แวร์ได้อย่างปลอดภัย

  1. ในคอนโซล Google Cloud ให้คลิกเมนูการนำทาง (ไอคอนแฮมเบอร์เกอร์) ที่มุมซ้ายบน เลือก Google Auth Platform > ไคลเอ็นต์ (หรือ API และบริการ > ข้อมูลเข้าสู่ระบบ หากไม่เห็น Google Auth Platform) คลิกสร้างไคลเอ็นต์ (หรือสร้างข้อมูลเข้าสู่ระบบ > รหัสไคลเอ็นต์ OAuth)
  2. เลือกเว็บแอปพลิเคชันเป็นประเภทแอปพลิเคชัน
  3. ตั้งชื่อว่า Workspace Agent Production
  4. ในส่วน Authorized redirect URIs ให้เพิ่ม URI ต่อไปนี้
    • คลิกเพิ่ม URI แล้วป้อน https://vertexaisearch.cloud.google.com/oauth-redirect
    • คลิกเพิ่ม URI อีกครั้ง แล้วป้อน https://vertexaisearch.cloud.google.com/static/oauth/oauth.html
  5. เลือกใช้ไคลเอ็นต์นี้สำหรับ Agent ที่ทำงานด้วยระบบ AI เพื่อเปิดใช้แฟล็กการแยกประเภท is_agentic ในไคลเอ็นต์ OAuth
  6. คลิกสร้าง ในกล่องโต้ตอบ "สร้างไคลเอ็นต์ OAuth แล้ว" (หรือจากรายการไคลเอ็นต์) ให้คัดลอกรหัสไคลเอ็นต์และรหัสลับไคลเอ็นต์ คุณจะต้องใช้ข้อมูลเหล่านี้เมื่อลงทะเบียน Agent ใน Gemini Enterprise

สร้างแอป Gemini Enterprise

  1. ในคอนโซล Google Cloud ให้ไปที่หน้า Gemini Enterprise โดยทำดังนี้

  1. คลิกจัดการในการ์ด Gemini Enterprise
  2. คลิกสร้างแอป
  3. ในส่วน Gemini Enterprise ให้คลิกสร้าง
  4. ในช่องชื่อแอปของคุณ ให้ป้อนชื่อแอป รหัสแอปจะปรากฏใต้ชื่อแอป
  5. ในช่องชื่อภายนอกของบริษัทหรือองค์กร ให้ป้อนชื่อบริษัทหรือองค์กร สำหรับบทแนะนำนี้ คุณสามารถใช้ Cymbal Bank
  6. เลือก global (Global) เป็นตำแหน่งของแอป
  7. คลิกต่อไป

ลงทะเบียน Custom Agent

  1. เปิดคอนโซล Gemini Enterprise โดยทำดังนี้

  1. เลือกแอปที่ใช้งานอยู่ ไปที่ตัวแทน แล้วคลิก + เพิ่มตัวแทน > เพิ่มตัวแทนที่กำหนดเองผ่านรันไทม์ของตัวแทน
  2. ในส่วนการให้สิทธิ์ ให้คลิกเพิ่มการให้สิทธิ์
    • ชื่อการให้สิทธิ์: 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.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
      
  3. คลิกเสร็จสิ้น แล้วคลิกถัดไป
  4. ในส่วนการกำหนดค่า ให้ทำดังนี้
    • ชื่อ 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.
      
    • Agent Runtime reasoning engine: วางชื่อทรัพยากรของเครื่องมือที่คัดลอกมาจากเอาต์พุต adk deploy
  5. คลิกสร้าง

ลองใช้ Agent ใน Gemini Enterprise

คุณสามารถโต้ตอบกับ Agent ได้โดยใช้เวอร์ชันตัวอย่างของคอนโซล Google Cloud (เร็วที่สุดสำหรับนักพัฒนาซอฟต์แวร์) หรือเว็บแอป Gemini Enterprise (ประสบการณ์ของผู้ใช้ปลายทาง)

ตัวเลือกที่ 1: เวอร์ชันตัวอย่างของคอนโซล Google Cloud

  1. ในคอนโซล Google Cloud ให้ไปที่หน้า Gemini Enterprise โดยทำดังนี้

  1. ในเมนูการนำทาง ให้คลิกแอป แล้วเลือกแอปที่คุณเพิ่งสร้าง
  2. คลิกแสดงตัวอย่างหรือคลิกเปิดตัวอย่างที่ด้านขวาบน
  3. ป้อนคำค้นหาต่อไปนี้ในแถบค้นหา
    Search for files in Drive related to 'Project Milestone', summarize them, and tell me if I have any meetings with the project owner today.
    
  4. กด Enter เพื่อส่งคำค้นหาและดูผลลัพธ์ในคอนโซลโดยตรง

ตัวเลือกที่ 2: เว็บแอป Gemini Enterprise

  1. เปิดอินเทอร์เฟซเว็บแอป Gemini Enterprise
  2. ไปที่เมนู ☰ > Agent แล้วเลือก Workspace Pro Agent ในส่วนจากองค์กรของคุณ
  3. พิมพ์คำค้นหาเดียวกันกับในตัวเลือกตัวอย่างคอนโซล Google Cloud
  4. คลิกให้สิทธิ์เมื่อได้รับข้อความแจ้งให้ทำตามขั้นตอนความยินยอมของผู้ใช้ OAuth
  5. Agent จะทำงานต่างๆ ได้อย่างราบรื่นในหลายบริการโดยใช้โปรโตคอล MCP

7. ล้างข้อมูล

โปรดล้างทรัพยากรเพื่อหลีกเลี่ยงค่าใช้จ่ายที่ไม่จำเป็น โดยทำดังนี้

ตัวเลือกคอนโซล

ไปที่แดชบอร์ด API และบริการ เลือกบริการ MCP ที่คุณเปิดใช้ (เช่น MCP ของปฏิทิน, MCP ของ Gmail) แล้วคลิกปิดใช้ API ลบรหัสไคลเอ็นต์ OAuth ในส่วนแพลตฟอร์มการตรวจสอบสิทธิ์ของ Google > ไคลเอ็นต์ และลบการติดตั้งใช้งาน 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 \
  workspacemcp.googleapis.com

8. ขอแสดงความยินดี

ยินดีด้วย คุณได้สร้าง ทดสอบ และติดตั้งใช้งาน AI Agent ของ ADK แบบเขียนโค้ดระดับมืออาชีพที่เชื่อมต่อโดยตรงกับเซิร์ฟเวอร์ MCP อย่างเป็นทางการของ Google Workspace เรียบร้อยแล้ว

สิ่งที่คุณได้เรียนรู้

  • วิธีเปิดใช้บริการ MCP ของ Google Workspace ใน Google Cloud
  • วิธีจัดการข้อมูลเข้าสู่ระบบ OAuth สำหรับการทดสอบ ADK ในเครื่องโดยใช้ส่วนหัวแบบคงที่
  • วิธีใช้การแทรกโทเค็นแบบไดนามิกโดยใช้ header_provider สำหรับ Agent เวอร์ชันที่ใช้งานจริง
  • วิธีติดตั้งใช้งาน Agent ของ ADK ในรันไทม์ของ Agent ของ GEAP และลงทะเบียนใน Gemini Enterprise

เอกสารอ้างอิง