עיגון סוכני AI באמצעות הקשר גיאו-מרחבי בעולם האמיתי באמצעות Maps Grounding Lite MCP

פיתוח סוכני AI הוא שלב משמעותי באבולוציה של פיתוח תוכנה, שמאפשר למערכות לבצע חשיבה מורכבת ולפעול באופן אוטונומי יותר. עם זאת, המודלים הבסיסיים שמפעילים את המערכות האלה מוגבלים באופן טבעי על ידי נתוני האימון שלהם. בלי הקשר חיצוני, הם לא מודעים לתנאים בזמן אמת, כמו מזג האוויר הנוכחי בחוץ, אם עסק מקומי פתוח כרגע או המסלול היעיל ביותר ליעד.

במסמך הזה מוסבר איך לגשר על הפער בין חשיבה סטטית למציאות דינמית, על ידי עיגון סוכני ה-AI בנתונים גיאו-מרחביים מהימנים ממפות Google. תלמדו למה עיגון מרחבי הוא קריטי למשימות בעולם האמיתי, איך Model Context Protocol‏ (MCP) מפשט את השילוב של הכלים ואיך ליצור סוכן לתכנון נסיעות באמצעות Google Maps Grounding Lite MCP.

תרשים של סוכן לתכנון נסיעות
סוכן לתכנון נסיעות שמבוסס על MCP של מפות Google

למה נציגים צריכים ביסוס נתונים במפות Google

המעבר מתוכנה מסורתית ל-Agentic Workflows הוא מעבר מהנדסה דטרמיניסטית לתזמור הסתברותי. אנחנו עוברים ממערכות שרק יודעות דברים למנועי ביצוע פרואקטיביים שבאמת עושים דברים. כשאפליקציה חוצה את הקו הזה ופועלת בעולם הפיזי, רמת הדיוק הנדרשת משתנה לחלוטין.

מודלים גדולים של שפה (LLM) מבינים לוגיקה, אבל הזיכרון הפנימי שלהם הוא תמונת מצב היסטורית. לדוגמה, אם נציג מנהל שרשרת אספקה ומאשר בטעות את הזמינות של ספק או מסלול נסיעה, התוצאה היא בזבוז דלק, אי עמידה בהסכם רמת השירות (SLA) ושיבוש אמיתי של הפעילות העסקית. בארכיטקטורות של כמה סוכנים, תתמודדו עם בעיה של הזיות מדורגות. אם סוכן אחד בשרשרת ממציא מידע ומעביר נתונים שגויים לסוכן שני, כל המערכת מתחילה לבצע פעולות בעולם האמיתי על סמך שקר. אוטונומיה בלי אמת הופכת לאחריות עצומה.

העיגון מחייב את הנציג לחרוג ממשקלי האימון שלו. כשמאלצים את ה-AI לאחזר עובדות ניתנות לאימות בזמן אמת, כמו נתוני מקומות ונתוני ניתוב, נותנים לסוכן עיניים ואוזניים בזמן אמת, והופכים ניחוש סטטיסטי להחלטה תפעולית מושכלת.

למה MCP

‫Model Context Protocol‏ (MCP) הוא תקן פתוח שנועד לאפשר שילוב נתונים של כלים בשיטת Plug and Play.

בעבר, כדי לחבר מודל AI לממשקי API חיצוניים, היה צריך לכתוב קוד wrapper מותאם אישית ונוקשה. הייתם צריכים לטפל באופן ידני בעיצוב, בניתוח שגיאות ובתרגום של קריאות לפונקציות לכל יכולת בנפרד.

פרוטוקול MCP יוצר סטנדרטיזציה של שכבת השילוב הזו. אם תטמיעו לקוח MCP, האפליקציה שלכם תוכל לגלות ולהפעיל כלים שסופקו על ידי השרת באופן דינמי באמצעות פרוטוקול מאוחד. כך המפתחים יכולים להתמקד פחות בכתיבת לוגיקה חוזרת של שילוב API, ויותר בתכנון רשתות מתקדמות של סוכנים.

‫Google Maps Grounding Lite MCP

‫Google Maps Grounding Lite MCP הוא שרת MCP מנוהל באופן מלא שמתארח ב-Google, ואפשר לשלב אותו ישירות בכל מסגרת תואמת של סוכני AI.

נכון לעכשיו, השרת מספק שלושה כלים עיקריים לביסוס:

  • חיפוש מקומות: אתם יכולים לבקש מידע על מקומות ולקבל סיכומים של נתוני מקומות שנוצרו על ידי AI, וגם מזהי מקומות, קואורדינטות של קווי רוחב ואורך וקישורים למפות Google לכל אחד מהמקומות שנכללים בסיכום. אתם יכולים להשתמש במזהי המקומות ובקואורדינטות של קווי האורך והרוחב שמוחזרים עם ממשקי API אחרים של Google Maps Platform כדי להציג מקומות במפה.
  • חיפוש מזג אוויר: בקשת מידע על מזג האוויר והצגת התנאים הנוכחיים, תחזיות לפי שעה ותחזיות יומיות.
  • חישוב מסלולים: בקשת מידע על מסלולי נסיעה או הליכה בין שני מיקומים, וקבלת מידע על המרחק ומשך הזמן של המסלול.

כדי לגשת לשירות, אתם יכולים להשתמש במפתח API או ב-OAuth. בפלטפורמה של מפות Google יש מפתח API חינמי להדגמה, שנועד במיוחד לעזור למפתחים להתחיל ליצור אב טיפוס באופן מיידי.

ארכיטקטורת MCP של עיגון במפות Google
ארכיטקטורת MCP של Maps Grounding

שיטות מומלצות לשילוב MCP של ביסוס במפות Google

כדי למקסם את הרלוונטיות של הנתונים ולמנוע הזיות מבניות, כדאי לעגן את הוראות המערכת של הנציג באסטרטגיות הליבה הבאות: * היו מפורשים וספציפיים: הנחו את הנציג להשתמש במיקומים מדויקים. החיפוש "סנטרל פארק, ניו יורק" יניב תוצאות טובות יותר מאשר "ניו יורק", בדיוק כמו שהחיפוש "פריז, צרפת" מונע בלבול עם פריז, טקסס.

  • פירוק שאילתות כלליות: אם המשתמשים מזינים בקשות מעורפלות כמו "רעיונות לדייט", כדאי להנחות את הסוכן לפרק את המשימה לחיפושי משנה ספציפיים כמו "מסעדות רומנטיות", "בתי קולנוע" או "ברים של קוקטיילים".

  • קודם מחפשים, אחר כך חוקרים: קודם מבצעים חיפוש רחב (למשל, "מסעדות יפניות עם כניסות נגישות שפתוחות ביום ראשון"). להציג למשתמש אפשרויות, ואז להריץ שאילתת המשך כדי לאחזר פרטים ספציפיים, כמו מספר טלפון של המקום שנבחר.

  • אל תמציאו מזהי מקומות: מזהי מקומות הם החיבור הקריטי בין שירותי Google Maps Platform. חשוב לוודא שהנציג יודע שהוא צריך להשתמש רק במזהי מקומות שמוחזרים באופן מפורש על ידי הכלי search_places, ולא לנסות ליצור מזהים משלו.

הטמעת סוכן לתכנון נסיעות באמצעות Google ADK

בקטע הזה נסביר איך ליצור סוכן לתכנון נסיעות באמצעות מסגרת הערכה לפיתוח סוכנים (ADK) של Google. אם ה-ADK לא מותקן, עיינו במסמך הפיתוח של Google ADK.

קל לשלב את שרת ה-MCP של מפות Google במסגרת של סוכן כמו 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 שמוגדר כברירת מחדל, מריצים את הפקודה הזו בספריית הפרויקט travel-concierge-google-maps-mcp:

adk web

אינטראקציה בממשק המשתמש:

  • טוענים את ממשק המשתמש בכתובת http://127.0.0.1:8000 בדפדפן.
  • אפשר לנסות הנחיות כמו:
    • "אני אהיה בתל אביב ביום שבת. תתכנן לי טיול ליום אחד".
    • "תמצא בתי קפה ליד פארק הירקון ותראה לי את המנות המומלצות בתפריט".
    • "Get directions from GooglePlex to SFO"

כשהסוכן מקבל את ההנחיה, המתכנן מעריך את כוונת המשתמש. הוא מזהה את הצורך בנתוני מיקום ומזג אוויר, ומפעיל באופן אוטונומי את הכלים lookup_weather, ‏ search_places ו-compute_routes באמצעות שרת ה-MCP. לאחר מכן, הסוכן יוצר מסלול נסיעה שמבוסס על עובדות בשביל המשתמש.

סיכום

המעבר ל-AI אקטיבי פותח אפשרויות חדשות לגמרי בתחומים כמו לוגיסטיקה, נסיעות וקמעונאות. אבל כדי שהאוטונומיה תהיה אמיתית, היא צריכה להתבסס על אמת מוצקה.

כשמשתמשים ב-Model Context Protocol לצד Google Maps Grounding Lite, לא צריך להתמודד עם הקשיים של שילובי API מותאמים אישית, והסוכנים מקבלים את העיניים והאוזניים שהם צריכים בזמן אמת. כשמעגנים את המודלים בנתונים מרחביים בזמן אמת, הם מקבלים החלטות תפעוליות על סמך מה שקורה בעולם הפיזי כרגע, ולא על סמך תמונת מצב קפואה מנתוני האימון שלהם.

הפעולות הבאות

מחברים ראשיים:

Teresa Qin | Google Maps Platform DevX Engineer