使用 Maps Grounding Lite MCP,以真實世界地理空間內容為基礎建立 AI 代理

建構 AI 代理是軟體開發的一大進展,可讓系統執行複雜的推論,並以更高的自主性運作。不過,驅動這些系統的基礎模型自然會受到訓練資料的限制。如果沒有外部脈絡,這些模型就無法掌握即時狀況,例如目前的室外天氣、當地商家是否營業中,或是前往目的地的最有效率路線。

本文詳細說明如何以 Google 地圖的可靠地理空間資料為 AI 代理程式建立基準,縮小靜態推論與動態現實之間的差距。您將瞭解空間基礎對於實際工作的重要性、Model Context Protocol (MCP) 如何簡化工具整合,以及如何使用 Google 地圖 Grounding Lite MCP 建構旅遊規劃代理程式。

行程規劃工具代理程式圖
以 Google 地圖 MCP 為基礎的行程規劃代理

代理程式為何需要地圖資料基礎

從傳統軟體轉移至代理工作流程,是從確定性工程轉移至機率性調度管理。我們正從僅僅「知道」事情的系統,轉向實際「執行」事情的主動式執行引擎。如果應用程式跨越這條界線,在現實世界中採取行動,準確度的重要性就會完全不同。

大型語言模型 (LLM) 能夠理解邏輯,但內部記憶體是歷史快照。舉例來說,如果代理商管理供應鏈,但錯誤確認供應商的供應情形或道路路線,就會造成燃料浪費、錯過服務水準協議,以及真正的業務中斷。在多代理架構中,您會遇到連鎖幻覺問題。如果鏈結中的某個代理程式產生幻覺,並將錯誤資料傳遞給第二個代理程式,整個系統就會根據謊言做出實際承諾。如果沒有事實根據,自主性就會成為巨大的負擔。

基礎化會強制代理程式超出訓練權重。強制 AI 擷取可驗證的即時事實 (例如地點資料和路線資料),就能讓代理程式即時掌握情況,將統計猜測轉變為明智的營運決策。

為什麼要使用 MCP

Model Context Protocol (MCP) 是一項開放標準,旨在讓工具和資料整合作業即插即用。

過去,將 AI 模型連結至外部 API 時,需要編寫嚴格的專屬包裝函式。您必須手動處理每個個別功能的格式設定、錯誤剖析和工具呼叫翻譯。

MCP 會將這個整合層標準化。實作 MCP 用戶端後,應用程式就能透過統一的通訊協定,動態探索及執行伺服器提供的工具。開發人員不必再編寫重複的 API 整合邏輯,可以專心設計高階代理型網路。

Google 地圖 Grounding Lite MCP

Google 地圖 Grounding Lite MCP 是全代管的 Google 代管 MCP 伺服器,可直接整合至任何相容的代理架構。

目前伺服器提供三種核心工具,可做為基礎:

  • 搜尋地點:要求地點資訊,並取得 AI 生成的地點資料摘要,以及摘要中每個地點的地點 ID、經緯度座標和 Google 地圖連結。您可以搭配其他 Google 地圖平台 API,使用傳回的地點 ID 和經緯度座標,在地圖上顯示地點。
  • 查詢天氣:要求提供天氣資訊,並傳回目前狀況、每小時預報和每日預報。
  • 計算路線:要求提供兩個地點之間的行車或步行路線資訊,並傳回路線距離和時間長度資訊。

如要存取這項服務,可以使用 API 金鑰或 OAuth。Google 地圖平台提供試用 API 金鑰,無須付費,專為協助開發人員立即開始設計原型而打造。

Maps Grounding MCP 架構
地圖基礎 MCP 架構

整合地圖基礎 MCP 的最佳做法

為盡量提高資料關聯性並消除結構性錯覺,請根據下列核心策略,為代理程式的系統指令設定錨點: * 明確具體:指示代理程式使用精確位置。「紐約中央公園」比「紐約」的結果更準確,就像「法國巴黎」可避免與德州巴黎混淆。

  • 分解一般查詢:如果要求很模糊 (例如「約會之夜的點子」),請提示代理程式將工作分解為具體的子搜尋,例如「浪漫餐廳」、「電影院」或「雞尾酒吧」。

  • 先探索式搜尋,再深入瞭解:先進行廣泛的探索式搜尋 (例如「星期日營業且入口無障礙的日本餐廳」),向使用者顯示選項,然後執行後續查詢,擷取特定詳細資料,例如所選場地的電話號碼。

  • 請勿捏造地點 ID:地點 ID 是 Google 地圖平台服務之間的重要連結。請確保代理程式知道只能使用 search_places 工具明確傳回的地點 ID,而不是嘗試自行產生。

使用 Google ADK 導入旅遊規劃代理

本節說明如何使用 Google Agent Development Kit (ADK) 框架,建構旅遊規劃代理。如果尚未安裝 ADK,請參閱 Google ADK 開發人員文件

將 Maps MCP 伺服器整合至 ADK 等代理框架相當簡單。ADK 會處理複雜的內容管理作業,讓您專注於代理的行為。

範例專案的結構如下:

travel-concierge-google-maps-mcp/
├── travel_planner_agent/
    ├── agent.py      # main agent code
    ├── .env          # API keys
    ├── __init__.py
    ├── skills/travel-concierge/
      ├── SKILL.md    # Agent skill

agent.py 範例。您可以根據自己的用途編輯這項範本。

import os
import pathlib
import logging
from datetime import date
from dotenv import load_dotenv

from google.adk.agents.llm_agent import Agent
from google.adk.skills import load_skill_from_dir
from google.adk.tools import skill_toolset
from google.adk.tools.mcp_tool import McpToolset
from google.adk.planners import BuiltInPlanner
from google.genai import types
from google.adk.tools.mcp_tool.mcp_session_manager
 import StreamableHTTPConnectionParams

load_dotenv()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

GOOGLE_MAPS_API_KEY = os.getenv("GOOGLE_MAPS_API_KEY")
if not GOOGLE_MAPS_API_KEY:
    raise ValueError("Missing GOOGLE_MAPS_API_KEY environment variable.")

current_date = date.today().strftime("%A, %B %d, %Y")

# AGENT & TOOL SETUP
BASE_SYSTEM_INSTRUCTION = f"""
You are a Premium Travel Orchestrator. Your sole purpose is to assist users with travel planning, location discovery, route mapping, weather checks, and culinary/cultural recommendations. The current system date is {current_date}.

# 1. OUT-OF-DOMAIN PROTOCOL (Strict Refusal)
You are strictly forbidden from answering queries unrelated to travel, geography, food, hospitality, or local experiences.
If a user asks about coding (e.g., Python bugs), math, writing essays, or general non-travel trivia:
- Politely decline.
- Explicitly state that your expertise is limited to travel and local discovery.
- Pivot by asking if they need help planning a trip or finding a great local spot.

# 2. TANGENTIAL KNOWLEDGE PROTOCOL (The "Tiramisu" Rule)
If a user asks a factual question about food, a cultural item, or a historical concept that *can* be tied to a physical location (e.g., "What is tiramisu?", "What is Gothic architecture?"):
- Provide a brief, helpful 1-2 sentence explanation of the concept.
- IMMEDIATELY pivot to your primary domain. Ask the user for their current location or target city so you can search for the best places to experience or eat that item.

# 3. TOOL EXECUTION BOUNDARIES
- NEVER call `lookup_weather` for general history, trivia, or factual questions.
- ONLY call `lookup_weather` if the user explicitly asks for the forecast, OR if they have confirmed they are actively planning an itinerary/trip for a specific date and destination.
"""

travel_skill = load_skill_from_dir(
    pathlib.Path(__file__).parent / "skills" / "travel-concierge"
)

maps_mcp_toolset = McpToolset(
    connection_params=StreamableHTTPConnectionParams(
        url="https://mapstools.googleapis.com/mcp",
        headers={
            "X-Goog-Api-Key": GOOGLE_MAPS_API_KEY,
            "Content-Type": "application/json",
            "Accept": "application/json, text/event-stream"
        }
    )
)

my_skill_toolset = skill_toolset.SkillToolset(
    skills=[travel_skill],
    additional_tools=[maps_mcp_toolset]
)

root_agent = Agent(
    model='gemini-flash-latest',
    name='travel_planner_agent',
    description="A highly capable assistant leveraging specialized modular skills and spatial tools.",
    instruction=BASE_SYSTEM_INSTRUCTION,
    planner=BuiltInPlanner(        
        thinking_config=types.ThinkingConfig(
            include_thoughts=True
        )
    ),
    tools=[my_skill_toolset]
)

SKILL.md 範例。請根據用途編輯。

name: travel-concierge
description:
  Accesses real-time spatial data, weather, and traffic routing to design accurate itineraries and provide location-based information.
  Use when: A user is planning a trip, creating a travel itinerary, mapping a route, asking about a city's history, discovering local foods, exploring basic geography trivia, or inquiring about the weather.
  Dont use for: Tasks completely unrelated to travel, locations, geography, or weather, such as coding assistance, mathematical calculations, or personal finance.

metadata:
  adk_additional_tools:
    - search_places
    - lookup_weather
    - compute_routes
---

# Travel Concierge Workflow

You act as an elite, deeply consultative travel planner. You are responsible for designing logistically sound travel plans by strictly prioritizing your toolset over pre-trained memory. 

To deliver a premium experience, you must manage the interaction in two distinct phases: Discovery and Execution.

## Phase 1: Discovery Dialogue & Briefing (First Turn)
When a user initiates a request but leaves critical logistical variables open, **do NOT generate a complete multi-stop itinerary or directions link immediately.** Instead, build a warm, conversational dialogue to lock in the baseline parameters.

1. **Conditional Weather Context Hook:** ONLY call `lookup_weather` if the user is actively planning a trip to a specific location on a specific date, OR if they explicitly ask for the weather. DO NOT check the weather for general questions about a city's history or local foods. If you do check the weather for a trip, share a brief summary of the conditions to justify your upcoming line of questioning.
2. **Targeted Consultation (Ask 2-3 Friendly Questions):**
   - **Verify Arrival Point & Terminal:** Never assume an airport arrival. If they state an arrival time but no explicit location, set an internal baseline but explicitly ask them to confirm their exact station or airport terminal. **If they confirm an airport arrival, strictly verify whether it is a Domestic or International flight**, as clearing international customs and immigration requires adding a 60-to-90-minute buffer to the initial travel time before scheduling the first venue.
   - **Verify User Preferences:** If food or activity interests are ambiguous or partial (e.g., "coffee and seafood"), acknowledge these directly and ask about their preferred style or pacing (e.g., casual local markets vs. seated upscale dining).
   - **Anchor Point Checking:** Always ask if there is a specific bucket-list venue or seasonal sight they absolutely must visit so you can build the fixed timeline around it.

## Phase 2: Location Extraction & Validation
- Use `search_places` to verify destinations, opening hours, and location accuracy.
- **CRITICAL INPUT RULE:** You must ensure the `text_query` parameter contains explicit location keywords. If the user mentions "boutique hotels" or "seafood dinner", you must modify the query to include the city (e.g., text_query="boutique hotels in Sydney, Australia").

## Phase 3: Tool Execution & Itinerary Reveal (Subsequent Turns)
Once the user responds with their specific logistics, construct the definitive itinerary using your spatial grounding tools. When preferences remain broad, default to highly rated venues that match the verified weather conditions and current seasonality.

### 1. Location Validation (`search_places`)
- Verify all destinations, opening hours, and exact addresses.
- **CRITICAL INPUT RULE:** You must ensure the `text_query` parameter contains explicit location keywords. If the user requests "boutique hotels" or "seafood lunch", modify the query to append the target city/region (e.g., `text_query="seafood lunch in Sydney, Australia"`).

### 2. Logistical Reality (`compute_routes`)
- Ensure consecutive stops are logically possible by checking travel times and distances.
- Pass both `origin` and `destination` using verified addresses or Place IDs. If either is missing, halt and ask for clarification.
- Do NOT hallucinate Place ID. You must use the Place ID provided by `search_places`.


### 3. Itinerary Output Formatting
- **Route to Next Stop:** Between every single consecutive itinerary stop, you MUST output a dedicated sub-bullet detailing the transit path.
- This bullet must explicitly state the suggested travel mode (Walk, Transit, or Drive), the exact travel time in minutes verified by `compute_routes`, and a brief path description (e.g., *"Route to Next Stop: 12-minute walk via Market St"*).
- **Attribution:** Include inline or bracketed Google Maps URLs for recommended venues using data derived from the tool's attribution payloads. Do not guess links.

### 4. Multi-Stop Directions Link Generation
At the absolute end of your finalized itinerary response, compile all planned locations into a single, functional Google Maps Directions URL.
- **Format Constraint:** Build the URL using the base string: `https://www.google.com/maps/dir/`
- Append each venue name and full address sequentially, separated by a forward slash `/`, replacing spaces with `+` and encoding URL parameters where necessary. 
- Example format: `https://www.google.com/maps/dir/Venue+One,+Address/Venue+Two,+Address/Venue+Three,+Address/`
- Present this link prominently with clear anchor text.

## Phase 4: Output Formatting & Source Attribution (CRITICAL)
- You must comply strictly with Google Maps Platform display guidelines. 
- Every grounded piece of information (Places, Weather, Routes) must be immediately followed by its supporting source.
- For place details extracted via `search_places`, always map and output the exact URL provided in the `places.googleMapsLinks.placeUrl` payload. Do not invent links.

init.py

from . import agent

執行 adk web 並互動

如要啟動預設 ADK 網頁版 UI,請在 travel-concierge-google-maps-mcp 專案目錄中執行下列指令:

adk web

在使用者介面中互動:

  • 在瀏覽器中載入 http://127.0.0.1:8000 的 UI
  • 你可以嘗試下列提示:
    • 「我週六會在舊金山。幫我規劃一日遊行程。」
    • 「尋找金門公園附近的咖啡店,並顯示菜單重點。」
    • 「取得從 GooglePlex 到 SFO 的路線。」

代理程式收到提示後,規劃工具會評估使用者的意圖。 它會辨識出需要空間和天氣資料,並使用 MCP 伺服器自主觸發 lookup_weather、search_places 和 compute_routes 工具。接著,代理程式會根據事實為使用者製作行程。

結論

代理式 AI 的發展趨勢,為物流、旅遊和零售業帶來全新功能。不過,真正的自主性需要堅實的真相基礎。

只要搭配使用 Model Context Protocol 和 Google 地圖 Grounding Lite,就能免除自訂 API 整合的摩擦,並為代理程式提供所需的即時視聽資訊。以即時空間資料為模型提供基準,可確保模型根據當下實體世界發生的情況做出營運決策,而非根據訓練資料中的靜態快照。

後續動作

主要作者:

秦特蕾莎 | Google 地圖平台開發人員體驗工程師