iT邦幫忙

2025 iThome 鐵人賽

DAY 14
0
生成式 AI

三十天解鎖上下文超能力:MCP 實戰系列 第 14

Day 14 - adk mcp 入門:安裝與發送第一個請求

  • 分享至 

  • xImage
  •  

大家好,歡迎來到鐵人賽第十四天!今天,我們寫程式!

在昨天的理論鋪墊後,我們知道 Agent Development Kit(adk) 是一個功能全面、對開發者友善的套件。今天,我們就要來實際感受它的簡潔與強大。我們將一步步完成從環境設定到成功發送 tools/list 請求的完整流程。

打開你的終端機和程式碼編輯器,讓我們開始吧!

一、準備我們的 Python 開發環境

在開始安裝任何東西之前,建立一個乾淨、獨立的 Python 開發環境是專業開發的第一步。我們將使用 Python 內建的 venv 來建立一個虛擬環境。

前提: 請確保你的電腦已安裝 Python 3.9 或更新版本。

第一步:建立並啟用虛擬環境

打開你的終端機 (Terminal 或 PowerShell),進入你的專案資料夾,然後依序輸入以下指令:

# 1. 建立一個名為 "venv" 的虛擬環境資料夾
python -m venv venv

# 2. 啟用虛擬環境
# Windows 系統:
venv\Scripts\activate

# macOS / Linux 系統:
source venv/bin/activate

截圖 2025-09-08 上午10.37.16

當你看到終端機提示符前面出現 (venv) 的字樣時,就代表你已經成功進入了這個獨立的開發環境。

為什麼要用虛擬環境?
它可以將這個專案所安裝的函式庫,與你電腦上其他 Python 專案完全隔離,避免版本衝突的惡夢。


二、安裝 google-adk 函式庫

在虛擬環境啟用後,安裝 google-adk 就只是一行指令的事。

pip install google-adk

pip 會自動下載並安裝 google-adk 及其所有相依套件。

三、建立我們的專案框架

我們將採用一個標準的 Python 套件結構。請打開你的終端機,在你想放置專案的地方,依序執行以下指令:

# 1. 建立最外層的專案資料夾
mkdir adk_ithelp
cd adk_ithelp

# 2. 建立我們主要的 Python 套件資料夾
mkdir multi_tool_agent

# 3. 建立必要的 Python 檔案
# macOS / Linux
touch multi_tool_agent/__init__.py multi_tool_agent/agent.py multi_tool_agent/.env

# Windows (PowerShell)
New-Item -ItemType File multi_tool_agent/__init__.py, multi_tool_agent/agent.py, .env

完成後,你的資料夾結構應該會是:

截圖 2025-09-08 上午11.08.18

四、編寫我們的第一個 MCP tools

打開一個名為 agent.py 的檔案,並將範例程式碼貼上:

import datetime
from zoneinfo import ZoneInfo
from google.adk.agents import Agent

def get_weather(city: str) -> dict:
    """Retrieves the current weather report for a specified city.

    Args:
        city (str): The name of the city for which to retrieve the weather report.

    Returns:
        dict: status and result or error msg.
    """
    if city.lower() == "new york":
        return {
            "status": "success",
            "report": (
                "The weather in New York is sunny with a temperature of 25 degrees"
                " Celsius (77 degrees Fahrenheit)."
            ),
        }
    else:
        return {
            "status": "error",
            "error_message": f"Weather information for '{city}' is not available.",
        }


def get_current_time(city: str) -> dict:
    """Returns the current time in a specified city.

    Args:
        city (str): The name of the city for which to retrieve the current time.

    Returns:
        dict: status and result or error msg.
    """

    if city.lower() == "new york":
        tz_identifier = "America/New_York"
    else:
        return {
            "status": "error",
            "error_message": (
                f"Sorry, I don't have timezone information for {city}."
            ),
        }

    tz = ZoneInfo(tz_identifier)
    now = datetime.datetime.now(tz)
    report = (
        f'The current time in {city} is {now.strftime("%Y-%m-%d %H:%M:%S %Z%z")}'
    )
    return {"status": "success", "report": report}


root_agent = Agent(
    name="weather_time_agent",
    model="gemini-2.0-flash",
    description=(
        "Agent to answer questions about the time and weather in a city."
    ),
    instruction=(
        "You are a helpful agent who can answer user questions about the time and weather in a city."
    ),
    tools=[get_weather, get_current_time],
)

程式碼解析

簡單來說,它做了三件事:

  1. 定義了一個只能查詢「紐約」天氣的假工具。
  2. 定義了一個只能查詢「紐約」時間的工具。
  3. 建立一個 AI 代理,並把上面這兩個工具交給它使用。

程式碼結構解析

整個程式碼可以分成三個主要部分:

1. 工具函式 (Tools)

這裡定義了兩個 Python 函式,它們是 AI 代理可以使用的「工具」。

get_weather(city: str)
  • 功能: 模擬查詢天氣。
  • 邏輯:
    • 它只認識一個城市:"new york" (不分大小寫)。
    • 如果輸入是「New York」,它會回傳一個包含成功訊息和天氣報告的字典。
    • 如果輸入是任何其他城市,它會回傳一個包含錯誤訊息的字典。
    • 注意: 這並不是一個真正的天氣 API,它回傳的資訊是寫死的。
# 範例:查詢天氣
get_weather("New York") 
# 回傳: {'status': 'success', 'report': 'The weather in New York is sunny...'}

get_weather("Taipei")
# 回傳: {'status': 'error', 'error_message': "Weather information for 'Taipei' is not available."}
get_current_time(city: str)
  • 功能: 查詢指定城市的目前時間。
  • 邏輯:
    • 和天氣函式一樣,它也只認識 "new york"
    • 如果輸入是「New York」,它會使用 zoneinfo 函式庫來取得「America/New_York」時區的現在時間,並格式化後回傳。
    • 如果輸入是其他城市,則回傳錯誤訊息。
# 範例:查詢時間
get_current_time("New York") 
# 回傳: {'status': 'success', 'report': 'The current time in New York is 2025-09-07 23:18:41 EST-0500'}
# (日期時間會是當下執行時的紐約時間)

2. AI 代理的設定 (Agent Initialization)

這部分是程式碼的核心,它使用 google.adk.agents 函式庫來建立一個 AI 代理。

root_agent = Agent(
    name="weather_time_agent",
    model="gemini-2.0-flash",
    description="Agent to answer questions about the time and weather in a city.",
    instruction="You are a helpful agent who can answer user questions about the time and weather in a city.",
    tools=[get_weather, get_current_time],
)
  • name: 給這個代理取一個名字,方便識別。
  • model: 指定代理背後使用的 AI 模型,這裡是 Google 的 gemini-2.0-flash
  • description: 簡短描述這個代理的功能,幫助模型或其他系統了解它的用途。
  • instruction: 給予 AI 代理的系統指令角色設定。這會影響它回答問題的語氣和風格。這裡指示它要扮演一個樂於助人的角色。
  • tools: 最關鍵的部分。這裡把前面定義的 get_weatherget_current_time 這兩個函式註冊為該代理可以使用的工具。

運作流程

當你對這個 root_agent 提出問題時(例如:「紐約現在幾點而且天氣如何?」),整個運作流程如下:

  1. 理解意圖: gemini-2.0-flash 模型會分析你的問題,理解你想要查詢「紐約」的「時間」和「天氣」。
  2. 選擇工具: 模型會查看它擁有的 tools 列表 ([get_weather, get_current_time]),判斷需要使用這兩個工具來完成任務。
  3. 執行工具:
    • 代理會自動呼叫 get_current_time("new york")
    • 代理會自動呼叫 get_weather("new york")
  4. 整合資訊: 代理會收到這兩個函式回傳的結果 (包含時間和天氣報告的字典)。
  5. 生成回覆: 最後,gemini-2.0-flash 模型會根據收到的資訊和它的 instruction ("You are a helpful agent..."),用自然、流暢的語言生成最終的答案給你。

例如,它可能會回答:「紐約的現在時間是 2025-09-07 23:18:41,天氣晴朗,溫度為攝氏 25 度(華氏 77 度)。」

五、啟動伺-服器與執行客戶端

啟動 adk 內建的網頁

  • 開啟一個終端機,進入 adk_ithelp
  • 啟用虛擬環境 (source venv/bin/activatevenv\Scripts\activate)。
  • 啟動參考伺服器:adk web
  • 保持這個視窗運行。
    截圖 2025-09-08 上午11.25.23

如上圖所示,就已經成功啟動 dev UI了,可在瀏覽器直接開啟 http://127.0.0.1:8000

截圖 2025-09-08 上午11.28.54

如上圖,左側先選擇 multi_tool_agent ,就可以跟你的 agent 溝通囉!

截圖 2025-09-08 上午11.33.43

如上圖,可以成功使用剛剛撰寫的工具,可以取得紐約天氣和取得紐約時間


終端機執行

可在終端機打上下方指令

adk run multi_tool_agent

成果如下圖:
截圖 2025-09-08 上午11.49.52

六、今日總結

恭喜你!今天我們正式踏入了 Python MCP 的世界。這是一個意義非凡的里程碑!

讓我們回顧一下今天滿滿的收穫:

  1. 搭建了專業的開發環境: 我們學會了使用 venv 建立虛擬環境,並搭建了一個清晰、可擴展的專案框架。
  2. 安裝並使用了 google-adk 我們成功安裝了核心的 google-adk 函式庫,這是我們後續所有開發的基礎。
  3. 定義了第一個 Python 工具: 我們將簡單的 Python 函式 (get_weather, get_current_time),透過 Agenttools 參數,輕鬆地變成了 AI Agent 可以呼叫的能力。
  4. 啟動並測試了 ADK 開發介面: 我們學會使用 adk web 這個強大的內建工具,快速啟動一個網頁介面來與我們親手打造的 AI Agent 進行互動與測試。

最重要的是,我們親身體會到了 google-adk 的設計哲學——高度抽象與開發者友善。我們幾乎沒有去處理任何複雜的伺服器設定或協議細節,只是專注在編寫工具本身的邏輯,ADK 就為我們搞定了剩下的一切。

我們現在擁有了一個堅實的基礎和一個能運作的 Agent。雖然它目前只有寫兩個寫死的回覆,但這已經證明了整個流程是暢通的。

明天,我們將在這個專案的基礎上繼續擴展,改造我們的工具函式,讓它不再是寫死的假資料,而是去串接真實的外部 API,賦予我們的 AI Agent 獲取即時資訊的超能力!


上一篇
Day 13 - 踏入 Python MCP 的世界
下一篇
Day 15 - adk mcp tools:撰寫天氣狀況查詢tools和計算機tools
系列文
三十天解鎖上下文超能力:MCP 實戰17
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言