ADK এবং MCP ব্যবহার করে একটি গুগল ওয়ার্কস্পেস এআই এজেন্ট তৈরি করুন

১. ভূমিকা

এই কোডল্যাবে, আপনি এজেন্ট ডেভেলপমেন্ট কিট (ADK) ব্যবহার করে একটি প্রো-কোড এআই এজেন্ট তৈরি করতে শিখবেন, যা সরাসরি অফিসিয়াল গুগল ওয়ার্কস্পেস এমসিপি সার্ভারের সাথে সংযুক্ত হয়।

মডেল কনটেক্সট প্রোটোকল (MCP) একটি ওপেন স্ট্যান্ডার্ড যা এআই মডেলগুলোকে রিমোট সার্ভার দ্বারা প্রদত্ত টুলগুলো নিরাপদে ব্যবহার করতে সক্ষম করে। ADK হলো স্বয়ংক্রিয় এজেন্ট তৈরির জন্য গুগলের প্রো-কোড ফ্রেমওয়ার্ক। এই দুটিকে একত্রিত করে, আপনি আপনার Gmail, Google Drive, Google Calendar, Google Chat, এবং People ডেটার উপর ভিত্তি করে অত্যন্ত কাস্টমাইজড এজেন্ট তৈরি করতে পারেন।

উপলব্ধ টুল এবং কনফিগারেশন সম্পর্কিত সম্পূর্ণ ডকুমেন্টেশনের জন্য, Google Workspace MCP সার্ভার কনফিগার করুন দেখুন।

আপনি যা করবেন

  • আপনার গুগল ক্লাউড প্রোজেক্টে গুগল ওয়ার্কস্পেস এমসিপি পরিষেবাগুলি সক্রিয় করুন।
  • স্থানীয় পরীক্ষা এবং প্রোডাকশন ডেপ্লয়মেন্ট উভয়ের জন্য OAuth সম্মতি কনফিগার করুন এবং ক্রেডেনশিয়াল তৈরি করুন।
  • একটি স্থানীয় ADK এজেন্ট তৈরি করুন যা স্ট্যাটিক টোকেন ব্যবহার করে ৫টি ওয়ার্কস্পেস MCP সার্ভারের সাথে সংযোগ স্থাপন করে।
  • ডাইনামিক টোকেন ইনজেকশন ব্যবহার করে এমন একটি প্রোডাকশন-রেডি ADK এজেন্ট তৈরি করে Gemini Enterprise Agent Platform (GEAP) Agent Runtime-এ ডেপ্লয় করুন।
  • জেমিনি এন্টারপ্রাইজ-এর মধ্যেই আপনার কাস্টম এজেন্ট নিবন্ধন ও পরীক্ষা করুন।

আপনার যা যা লাগবে

  • একটি ওয়েব ব্রাউজার (যেমন, ক্রোম)।
  • বিলিং সক্ষম একটি গুগল ক্লাউড প্রজেক্ট।
  • একটি গুগল ওয়ার্কস্পেস অ্যাকাউন্ট (যেখানে স্মার্ট ফিচারগুলো চালু করা আছে)।
  • আপনার লোকাল মেশিনে পাইথন ৩.১১+ ইনস্টল করা আছে।
  • গুগল ক্লাউড সিএলআই ( gcloud ) ইনস্টল এবং চালু করা হয়েছে।

২. শুরু করার আগে

একটি গুগল ক্লাউড প্রজেক্ট তৈরি করুন বা নির্বাচন করুন

কনসোল বিকল্প

গুগল ক্লাউড কনসোলে , একটি গুগল ক্লাউড প্রজেক্ট নির্বাচন করুন বা তৈরি করুন।

CLI বিকল্প

একটি নতুন প্রজেক্ট তৈরি করুন এবং এটিকে সক্রিয় করুন:

gcloud projects create YOUR_PROJECT_ID
gcloud config set project YOUR_PROJECT_ID

এপিআইগুলি সক্রিয় করুন

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

চ্যাট অ্যাপটি কনফিগার করুন

গুগল চ্যাট এমসিপি সার্ভার ব্যবহার করতে হলে, আপনাকে আপনার গুগল ক্লাউড প্রজেক্টে একটি চ্যাট অ্যাপ কনফিগার করতে হবে।

  1. Google Cloud কনসোলে, Google Chat API অনুসন্ধান করুন এবং Google Chat API > Manage > Configuration-এ ক্লিক করুন।
  2. চ্যাট অ্যাপটি সেট আপ করুন:
    • অ্যাপের নাম : ADK Workspace Agent
    • অবতার URL : https://developers.google.com/chat/images/quickstart-app-avatar.png
    • বিবরণ : MCP server connection for ADK Agent
    • ফাংশনালিটি- এর অধীনে, ‘এনেবল ইন্টারেক্টিভ ফিচারস’ বন্ধ করুন।
    • লগস-এর অধীনে, ত্রুটি লগ করার বিকল্পটি লগিং-এ নির্বাচন করুন।
  3. সংরক্ষণ করুন- এ ক্লিক করুন।

৩. OAuth সম্মতি এবং ক্লায়েন্ট কনফিগার করুন

গুগল ওয়ার্কস্পেস এমসিপি সার্ভারগুলো নিরাপদ প্রমাণীকরণের জন্য OAuth 2.0 ব্যবহার করে। আপনাকে অবশ্যই OAuth সম্মতি স্ক্রিনটি কনফিগার করতে হবে এবং দুটি পৃথক ক্লায়েন্ট আইডি তৈরি করতে হবে: একটি স্থানীয় ডেভেলপমেন্টের জন্য এবং অন্যটি ডেপ্লয় করা এজেন্টের জন্য।

  1. গুগল ক্লাউড কনসোলে, উপরের বাম কোণায় থাকা নেভিগেশন মেনুতে (হ্যামবার্গার আইকন) ক্লিক করুন। Google Auth Platform > Branding নির্বাচন করুন (অথবা যদি Google Auth Platform দৃশ্যমান না থাকে, তাহলে APIs & Services > OAuth consent screen নির্বাচন করুন)।
  2. অ্যাপের তথ্য কনফিগার করুন :
    • অ্যাপের নাম : Workspace ADK Agent
    • ব্যবহারকারী সহায়তা ইমেল : আপনার ইমেল নির্বাচন করুন।
  3. দর্শক নির্ধারণ করুন : অভ্যন্তরীণ নির্বাচন করুন।
  4. যোগাযোগের তথ্য নির্ধারণ করুন: আপনার ইমেল ঠিকানা লিখুন, তারপর তৈরি করুন-এ ক্লিক করুন।
  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
    
  6. অ্যাড টু টেবিল-এ ক্লিক করুন, তারপর আপডেট করুন এবং সবশেষে সেভ করুন

স্থানীয় ডেভেলপমেন্টের (ডেস্কটপ অ্যাপ) জন্য ক্লায়েন্ট আইডি তৈরি করুন

  1. In the Google Cloud console, navigate to Google Auth Platform > Clients (or APIs & Services > Credentials ). Click Create Credentials (or Create Client ) and select OAuth client ID .
  2. অ্যাপ্লিকেশনের ধরন হিসেবে ডেস্কটপ অ্যাপ নির্বাচন করুন।
  3. এর নাম দিন Workspace Agent Local
  4. Create-এ ক্লিক করে JSON ফাইলটি ডাউনলোড করুন। ফাইলটি আপনার কম্পিউটারে client_secret.json নামে সেভ করুন।

৪. এজেন্টের উন্নয়ন এবং পরীক্ষণ

এই বিভাগে এজেন্ট এনভায়রনমেন্ট তৈরি করার পদ্ধতি বর্ণনা করা হয়েছে। আমরা টেস্টিংয়ের জন্য একটি স্ট্যাটিক টোকেন পদ্ধতি ব্যবহার করব, যেখানে আমরা gcloud ব্যবহার করে একটি OAuth টোকেন সংগ্রহ করে ADK-এর McpToolset এ পাঠাব। আপনি আপনার লোকাল মেশিন অথবা গুগল ক্লাউড শেল ব্যবহার করে এই ধাপগুলো অনুসরণ করতে পারেন।

আপনার ডেভেলপমেন্ট এনভায়রনমেন্ট সেট আপ করার জন্য লোকাল মেশিন অথবা গুগল ক্লাউড শেল থেকে আপনার পরিবেশ বেছে নিন। প্ল্যাটফর্ম জুড়ে সামঞ্জস্য নিশ্চিত করতে, উভয় পদ্ধতিতেই অথেনটিকেশনের জন্য একটি শেয়ার্ড পাইথন স্ক্রিপ্ট ব্যবহার করা হবে।

১. পরিবেশ ডিরেক্টরি সেট আপ করুন

একটি প্রজেক্ট ডিরেক্টরি তৈরি করতে এবং প্রয়োজনীয় প্যাকেজগুলো ইনস্টল করতে আপনার টার্মিনালে নিম্নলিখিত কমান্ডগুলো চালান।

  • গুগল ক্লাউড শেল-এর জন্য: প্রথমে, গুগল ক্লাউড কনসোলের উপরের ডানদিকের টুলবারে থাকা অ্যাক্টিভেট ক্লাউড শেল আইকনে ( >_ ) ক্লিক করুন।
  • স্থানীয় মেশিনের জন্য: আপনার স্ট্যান্ডার্ড টার্মিনালটি খুলুন।
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

২. পরিচয়পত্র ফাইল প্রস্তুত করুন

পূর্ববর্তী ধাপে ডাউনলোড করা client_secret.json ফাইলটি আপনাকে অবশ্যই আপনার gws-adk-agent ডিরেক্টরির রুটে রাখতে হবে।

  • Local Machine: Move or copy the downloaded client_secret.json file into the gws-adk-agent directory.
  • গুগল ক্লাউড শেল: ক্লাউড শেলে নিম্নলিখিত কমান্ডটি চালিয়ে ফাইলটি তৈরি করুন ( [PASTE_JSON_HERE] -এর জায়গায় আপনার আসল JSON কন্টেন্ট বসান):
cat << 'EOF' > client_secret.json
[PASTE_JSON_HERE]
EOF

৩. প্রমাণীকরণ করুন এবং .env ( auth.py ) তৈরি করুন।

প্রমাণীকরণ সামঞ্জস্যপূর্ণভাবে পরিচালনা করতে এবং পরিবেশ-নির্দিষ্ট CLI রাউটিং সমস্যা এড়াতে, আমরা অফিসিয়াল গুগল প্রমাণীকরণ লাইব্রেরি দ্বারা চালিত একটি কাস্টম পাইথন স্ক্রিপ্ট ব্যবহার করি। এই স্ক্রিপ্টটি 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. আপনার gws-adk-agent প্রোজেক্টের রুট ডিরেক্টরি থেকে ADK ওয়েব ইন্টারফেসটি চালু করুন:
    adk web
    
  2. Open http://localhost:8000 in your browser to chat with your agent.

আপনি যদি গুগল ক্লাউড শেলে থাকেন:

  1. From your gws-adk-agent project root directory, start the ADK web interface explicitly enforcing port 8080:
    adk web --port 8080 --allow_origins=*
    
  2. ক্লাউড শেল টুলবারের উপরের ডানদিকে থাকা ওয়েব প্রিভিউ বাটনে ক্লিক করুন এবং পোর্ট ৮০৮০-তে প্রিভিউ নির্বাচন করে ইন্টারফেসটি একটি নতুন ট্যাবে খুলুন।

বিকল্প ২: টার্মিনাল সিএলআই মোড (বিকল্প)

If you prefer to stay in the terminal or want to avoid setting up web browser previews, ADK provides a native interactive REPL chat mode.

From your gws-adk-agent project root directory, execute the following command (this works identically on both a Local Machine and Google Cloud Shell):

adk run workspace_agent

You will enter an interactive chat session directly in your shell:

Running agent gws_adk_agent, type exit to exit.

[user]:

আপনার এজেন্টকে প্ররোচিত করার চেষ্টা করুন

Regardless of the interface you chose, try testing the agent with queries that leverage the Workspace MCP tools:

What are my upcoming meetings this week?
Summarize the last 3 unread emails in my Gmail.

৫. প্রোডাকশন ডেপ্লয়মেন্ট

এজেন্টকে প্রোডাকশনে ডেপ্লয় করার জন্য আমরা হার্ডকোডেড লোকাল টোকেন ব্যবহার করতে পারি না। এর পরিবর্তে, যখন কোনো ব্যবহারকারী এজেন্টের সাথে ইন্টারঅ্যাক্ট করেন, তখন জেমিনি এন্টারপ্রাইজ প্ল্যাটফর্ম দ্বারা ইনজেক্ট করা OAuth অ্যাক্সেস টোকেনটি ডাইনামিকভাবে এক্সট্র্যাক্ট করতে আমরা ADK-এর header_provider ব্যবহার করি।

প্রোডাকশন এজেন্ট কোড তৈরি করুন

Create a directory package named enterprise_ai and create an agent.py file inside it:

mkdir -p enterprise_ai

Write the following content to 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 এজেন্ট রানটাইমে স্থাপন করুন

ADK CLI ব্যবহার করে আপনার প্রো-কোড এজেন্ট স্থাপন করুন:

adk deploy agent_engine \
  --project=$(gcloud config get-value project) \
  --region=us-central1 \
  --display_name="Workspace ADK Agent" \
  enterprise_ai

Wait for the deployment to finish and copy the generated Reasoning Engine resource name from the terminal output (eg, projects/PROJECT_ID/locations/us-central1/reasoningEngines/ENGINE_ID ).

৬. জেমিনি এন্টারপ্রাইজে নিবন্ধন করুন

Now, we bring the custom ADK agent into Gemini Enterprise so users can chat with it natively.

Create Client ID for Production (Web Application)

আপনার এজেন্টকে প্রোডাকশনে ডেপ্লয় করতে, আপনাকে অবশ্যই একটি ওয়েব অ্যাপ্লিকেশন ক্লায়েন্ট আইডি তৈরি করতে হবে। লোকাল টেস্টিংয়ের জন্য ব্যবহৃত ডেস্কটপ ক্লায়েন্টের থেকে ভিন্ন, একটি ওয়েব অ্যাপ্লিকেশন ক্লায়েন্ট একটি সুরক্ষিত, সার্ভার-সাইড OAuth ফ্লো সক্ষম করে। এটি GEAP এজেন্ট রানটাইমে হোস্ট করা এজেন্টকে, নির্দিষ্ট রিডাইরেক্ট URI ব্যবহার করে, Gemini Enterprise দ্বারা ফরোয়ার্ড করা ব্যবহারকারীর অথেনটিকেশন টোকেন নিরাপদে গ্রহণ করার সুযোগ দেয়। প্রোডাকশন পরিবেশে ব্যবহারকারীর পক্ষ থেকে এজেন্টের নিরাপদে Google Workspace ডেটা অ্যাক্সেস করার জন্য এই সেটআপটি প্রয়োজনীয়।

  1. Google Cloud কনসোলে, উপরের বাম কোণায় থাকা নেভিগেশন মেনুতে (হ্যামবার্গার আইকন) ক্লিক করুন। Google Auth Platform > Clients নির্বাচন করুন (অথবা যদি Google Auth Platform দেখা না যায়, তাহলে APIs & Services > Credentials নির্বাচন করুন)। Create Credentials (বা Create Client ) এ ক্লিক করুন এবং OAuth ক্লায়েন্ট আইডি নির্বাচন করুন।
  2. অ্যাপ্লিকেশনের ধরণ হিসেবে ওয়েব অ্যাপ্লিকেশন নির্বাচন করুন।
  3. এর নাম দিন Workspace Agent Production
  4. In the Authorized redirect URIs section, add the following URIs:
    • Click Add URI and enter https://vertexaisearch.cloud.google.com/oauth-redirect .
    • Click Add URI again and enter https://vertexaisearch.cloud.google.com/static/oauth/oauth.html .
  5. Click Create . In the "OAuth client created" pop-up (or from the Clients list), copy the Client ID and Client Secret . You will need these when registering the agent in Gemini Enterprise.

একটি জেমিনি এন্টারপ্রাইজ অ্যাপ তৈরি করুন

  1. In the Google Cloud console, go to the Gemini Enterprise page:

  1. জেমিনি এন্টারপ্রাইজ কার্ডের অধীনে, ম্যানেজ-এ ক্লিক করুন।
  2. অ্যাপ তৈরি করুন -এ ক্লিক করুন।
  3. জেমিনি এন্টারপ্রাইজ বিভাগে, ক্রিয়েট-এ ক্লিক করুন।
  4. In the Your app name field, enter a name for your app. Your app ID appears under the app name.
  5. In the External name of your company or organization field, enter the company or organization name. For this tutorial, you can use Cymbal Bank .
  6. Select global (Global) as the location for your app.
  7. চালিয়ে যান-এ ক্লিক করুন।

কাস্টম এজেন্ট নিবন্ধন করুন

  1. জেমিনি এন্টারপ্রাইজ কনসোলটি খুলুন:

  1. Select your active app, navigate to Agents , and click + Add agent > Add Custom agent via Agent Runtime .
  2. In the Authorizations section, click Add authorization :
    • Authorization name : workspace-adk-auth (Must exactly match CLIENT_AUTH_NAME in your Python code)
    • Client ID : Paste the Production Web Application Client ID created above.
    • Client secret : Paste the Production Web Application Client Secret created above.
    • টোকেন ইউআরআই : https://oauth2.googleapis.com/token
    • Authorization URI : Construct the URI by replacing YOUR_CLIENT_ID with the Client ID you copied in step 5 above:
      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
      
  3. Done-এ ক্লিক করুন, তারপর Next-এ ক্লিক করুন।
  4. কনফিগারেশন বিভাগে:
    • এজেন্টের নাম : 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 : Paste the engine resource name you copied from the adk deploy output.
  5. তৈরি করুন- এ ক্লিক করুন।

জেমিনি এন্টারপ্রাইজে এজেন্টকে চেষ্টা করে দেখুন

You can interact with your agent either using the Google Cloud Console Preview (fastest for developers) or the Gemini Enterprise Web App (end-user experience).

বিকল্প ১: গুগল ক্লাউড কনসোল প্রিভিউ

  1. In the Google Cloud console, go to the Gemini Enterprise page:

  1. In the navigation menu, click Apps and select the app you just created.
  2. Click Preview or click Open preview on the top right.
  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. Press Enter to submit the query and view the results directly in the console.

বিকল্প ২: জেমিনি এন্টারপ্রাইজ ওয়েব অ্যাপ

  1. আপনার জেমিনি এন্টারপ্রাইজ ওয়েব অ্যাপ ইন্টারফেসটি খুলুন।
  2. Go to Menu ☰ > Agents and select Workspace Pro Agent under From your organization .
  3. Type the same query as in the Google Cloud Console Preview option.
  4. Click Authorize when prompted to go through the OAuth user consent flow.
  5. The agent will execute tasks seamlessly across multiple services using the MCP protocol!

৭. পরিষ্কার করুন

To avoid unnecessary charges, clean up your resources:

কনসোল বিকল্প

API ও সার্ভিসেস ড্যাশবোর্ডে যান, আপনার সক্রিয় করা MCP সার্ভিসগুলো (যেমন, ক্যালেন্ডার MCP, জিমেইল MCP) নির্বাচন করুন এবং 'Disable API'-তে ক্লিক করুন। 'Google Auth Platform > Clients'- এর অধীনে থাকা OAuth ক্লায়েন্ট আইডিগুলো মুছে ফেলুন এবং Gemini Enterprise Console থেকে Reasoning Engine ডেপ্লয়মেন্টটি মুছে দিন।

CLI বিকল্প

Execute the following terminal commands to disable the MCP services:

# Disable Workspace MCP services
gcloud services disable calendarmcp.googleapis.com \
  chatmcp.googleapis.com \
  drivemcp.googleapis.com \
  gmailmcp.googleapis.com

৮. অভিনন্দন

Congratulations! You have successfully built, tested, and deployed a pro-code ADK AI agent connected directly to the official Google Workspace MCP servers.

আপনি যা শিখেছেন

  • How to enable Google Workspace MCP services in Google Cloud.
  • How to handle OAuth credentials for local ADK testing using static headers.
  • How to implement dynamic token injection using header_provider for production agents.
  • How to deploy an ADK agent to GEAP Agent Runtime and register it in Gemini Enterprise.

রেফারেন্স নথি