تزويد وكلاء الذكاء الاصطناعي بسياق جغرافي مكاني من العالم الحقيقي باستخدام بروتوكول Model Context Protocol (MCP) في Maps Grounding Lite

يمثّل إنشاء وكلاء الذكاء الاصطناعي تطورًا كبيرًا في مجال تطوير البرمجيات، ما يتيح للأنظمة إجراء عمليات استدلال معقّدة والعمل بقدر أكبر من الاستقلالية. ومع ذلك، فإنّ النماذج الأساسية التي تشغّل هذه الأنظمة تكون مقيّدة بطبيعتها ببيانات التدريب. بدون سياق خارجي، لا يمكنها معرفة الظروف في الوقت الفعلي، مثل حالة الطقس الحالية في الخارج، أو ما إذا كان نشاط تجاري محلي مفتوحًا الآن، أو المسار الأكثر كفاءة للوصول إلى وجهة معيّنة.

يوضّح هذا المستند كيفية سد الفجوة بين الاستدلال الثابت والواقع الديناميكي من خلال تزويد وكلاء الذكاء الاصطناعي ببيانات جغرافية مكانية موثوقة من "خرائط Google". ستتعرّف على أهمية الربط المكاني بالواقع للمهام الواقعية، وكيف يسهّل بروتوكول Model Context Protocol (MCP) دمج الأدوات، وكيفية إنشاء وكيل لتخطيط الرحلات باستخدام Google Maps Grounding Lite MCP.

مخطّط بياني لوكيل تخطيط الرحلات
وكيل "مخطِّط الرحلات" المستند إلى بروتوكول MCP في "خرائط Google"

لماذا يحتاج الوكلاء إلى الاستناد إلى بيانات الخرائط؟

إنّ الانتقال من البرامج التقليدية إلى سير العمل المستند إلى الوكلاء هو تحوّل من الهندسة الحتمية إلى التنسيق الاحتمالي. نحن ننتقل من أنظمة تقتصر على معرفة الأمور إلى محرّكات تنفيذ استباقية تنجز المهام فعليًا. عندما يتجاوز التطبيق هذا الخط ويتخذ إجراءً في العالم المادي، تتغير رهانات الدقة تمامًا.

تفهم النماذج اللغوية الكبيرة (LLM) المنطق، ولكن ذاكرتها الداخلية هي لقطة سابقة. على سبيل المثال، إذا كان الوكيل يدير سلسلة إمداد وأكّد بشكل غير صحيح مدى توفّر المورّد أو مسار الطريق، ستواجه مشكلة في إهدار الوقود وعدم الالتزام باتفاقية مستوى الخدمة وتعطُّل العمل الفعلي. وفي البُنى المتعددة الوكلاء، ستواجه مشكلة الهلوسة المتسلسلة. إذا قدّم وكيل واحد في السلسلة معلومات خاطئة ومرّرها إلى وكيل ثانٍ، سيبدأ النظام بأكمله في اتخاذ قرارات في العالم الحقيقي بناءً على معلومات غير صحيحة. الاستقلالية بدون حقيقة تصبح مسؤولية هائلة.

يتطلّب التحقّق من المصادر أن يتجاوز الوكيل أوزان التدريب الخاصة به. من خلال إجبار الذكاء الاصطناعي على جلب حقائق مباشرة يمكن التحقق منها، مثل بيانات الأماكن وبيانات المسارات، فإنك تمنح الوكيل عيونًا وآذانًا في الوقت الفعلي، ما يحوّل التخمين الإحصائي إلى قرار تشغيلي مدروس.

لماذا نستخدم بروتوكول MCP؟

‫"بروتوكول سياق النموذج" (MCP) هو معيار مفتوح مصمّم لتسهيل عمليات دمج الأدوات والبيانات.

في السابق، كان ربط نموذج ذكاء اصطناعي بواجهات برمجة تطبيقات خارجية يتطلّب كتابة برامج تضمين جامدة ومخصّصة. وكان عليك التعامل يدويًا مع التنسيق وتحليل الأخطاء وترجمات طلبات الأدوات لكل ميزة على حدة.

ويعمل بروتوكول MCP على توحيد طبقة التكامل هذه. من خلال تنفيذ عميل MCP، يمكن لتطبيقك استكشاف الأدوات التي يوفّرها الخادم وتنفيذها ديناميكيًا عبر بروتوكول موحّد. يؤدي ذلك إلى تحويل تركيز المطوّر من كتابة منطق برمجي متكرر لدمج واجهات برمجة التطبيقات إلى تصميم شبكات وكلاء عالية المستوى.

‫Google Maps Grounding Lite MCP

‫Google Maps Grounding Lite MCP هو خادم MCP مُدار بالكامل وتستضيفه Google، ويمكن دمجه مباشرةً في أي إطار عمل متوافق مع الوكلاء.

في الوقت الحالي، يوفّر الخادم ثلاث أدوات أساسية للتحقّق من صحة المعلومات:

  • البحث عن الأماكن: يمكنك طلب معلومات عن الأماكن والحصول على ملخّصات لبيانات الأماكن من إنشاء الذكاء الاصطناعي، بالإضافة إلى أرقام تعريف الأماكن وإحداثيات خطوط العرض والطول وروابط إلى "خرائط Google" لكل مكان مضمَّن في الملخّص. يمكنك استخدام أرقام تعريف الأماكن وإحداثيات خطوط العرض والطول التي تم عرضها مع واجهات برمجة تطبيقات أخرى في "منصة خرائط Google" لعرض الأماكن على الخريطة.
  • البحث عن الطقس: يطلب معلومات عن الطقس ويعرض الأحوال الجوية الحالية والتوقعات لكل ساعة والتوقعات اليومية.
  • احتساب المسارات: يمكنك طلب معلومات عن مسارات القيادة أو المشي بين موقعَين جغرافيَين والحصول على معلومات عن مسافة المسار ومدته.

للوصول إلى الخدمة، يمكنك استخدام مفتاح واجهة برمجة التطبيقات أو OAuth. توفّر "منصة خرائط Google" مفتاح واجهة برمجة تطبيقات تجريبيًا بدون أي تكلفة، وهو مصمّم خصيصًا لمساعدة المطوّرين في بدء إنشاء النماذج الأولية على الفور.

بنية MCP في Maps Grounding
بنية بروتوكول سياق النموذج (MCP) في ميزة "الربط بمصادر بيانات معروفة" في "خرائط Google"

أفضل الممارسات لدمج MCP الخاص بـ "الاستناد إلى خرائط Google"

لزيادة مدى صلة البيانات بالموضوع إلى أقصى حدّ والقضاء على الهلوسة البنيوية، يجب أن تركّز تعليمات نظام الوكيل على الاستراتيجيات الأساسية التالية: * الوضوح والتحديد: يجب توجيه الوكيل لاستخدام مواقع جغرافية دقيقة. على سبيل المثال، يؤدي البحث عن "برج خليفة، دبي" إلى نتائج أفضل من "دبي"، تمامًا كما يمنع البحث عن "باريس، فرنسا" حدوث التباس مع باريس، تكساس.

  • تقسيم طلبات البحث العامة: بالنسبة إلى الطلبات الغامضة مثل "أفكار لقضاء سهرة رومانسية"، اطلب من الوكيل تقسيم المهمة إلى عمليات بحث فرعية محدّدة مثل "مطاعم رومانسية" أو "دور سينما" أو "بارات كوكتيل".

  • البحث الاستكشافي أولاً، ثم الاستكشاف: ابدأ بإجراء بحث استكشافي واسع النطاق (مثلاً، "مطاعم يابانية بمداخل مناسبة لذوي الاحتياجات الخاصة تفتح يوم الأحد"). اعرض الخيارات على المستخدم، ثم نفِّذ طلب بحث متابعة لجلب تفاصيل محدّدة، مثل رقم هاتف المكان الذي تم اختياره.

  • عدم اختلاق أرقام تعريف الأماكن: أرقام تعريف الأماكن هي الرابط الأساسي بين خدمات "منصة خرائط Google". تأكَّد من أنّ الوكيل يعرف أنّه يجب استخدام أرقام تعريف الأماكن التي تعرضها أداة search_places بشكل صريح فقط، بدلاً من محاولة إنشاء أرقام تعريف خاصة به.

تنفيذ وكيل تخطيط للسفر باستخدام Google ADK

يوضّح هذا القسم كيفية إنشاء وكيل لتخطيط الرحلات باستخدام إطار عمل Google Agent Development Kit (ADK). إذا لم يكن لديك 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 في المتصفّح
  • جرِّب طلبات مثل:
    • "سأكون في القاهرة يوم السبت. ساعِدني في التخطيط لرحلة ليوم واحد".
    • "ابحث عن مقاهٍ بالقرب من حديقة غولدن غيت واعرض لي أبرز أصناف القائمة".
    • "أريد الحصول على الاتجاهات من GooglePlex إلى مطار سان فرانسيسكو الدولي".

عندما يتلقّى الوكيل الطلب، يقيّم المخطِّط نية المستخدم. يتعرّف على الحاجة إلى بيانات الموقع الجغرافي والطقس ويشغّل تلقائيًا أدوات lookup_weather وsearch_places وcompute_routes باستخدام خادم MCP. بعد ذلك، يجمع الوكيل برنامج رحلة مستندًا إلى الحقائق للمستخدم.

الخاتمة

يؤدي التحوّل نحو الذكاء الاصطناعي الوكيل إلى إتاحة إمكانات جديدة تمامًا في مجالات الخدمات اللوجستية والسفر والبيع بالتجزئة. ومع ذلك، يتطلّب الاستقلال الحقيقي أساسًا متينًا من الحقائق.

من خلال الاستفادة من بروتوكول Model Context مع Google Maps Grounding Lite، يمكنك التخلّص من صعوبات عمليات دمج واجهات برمجة التطبيقات المخصّصة ومنح وكلائك القدرة على رصد البيانات في الوقت الفعلي. من خلال ربط نماذجك بالبيانات المكانية المباشرة، يمكنك ضمان اتّخاذها قرارات تشغيلية استنادًا إلى ما يحدث في العالم المادي في الوقت الحالي، وليس استنادًا إلى لقطة ثابتة من بيانات التدريب.

الإجراءات التالية

المؤلفون الرئيسيون:

تيريزا تشين | مهندسة DevX في "منصة خرائط Google"