使用 Maps Grounding Lite MCP 为 AI 智能体提供真实世界的地理空间背景信息

构建 AI 智能体是软件开发领域的一项重大演变,它使系统能够执行复杂的推理并以更高的自主性运行。不过,驱动这些系统的基础模型自然会受到其训练数据的限制 。如果没有外部上下文,它们就无法了解 实时状况,例如当前外部天气、当地 商家是否正在营业,或者前往目的地的最有效路线。

本文档详细介绍了如何通过使用 Google 地图中的可信地理空间数据来为 AI 智能体提供接地信息,从而弥合静态推理与动态现实之间的差距。您将了解为什么空间接地对于现实世界的任务至关重要,Model Context Protocol (MCP) 如何简化工具集成,以及如何使用 Google Maps Grounding Lite MCP 构建旅行规划智能体。

行程规划工具代理图
依托 Maps MCP 的行程规划智能体

为什么智能体需要地图数据接地

从传统软件到智能体工作流的转变,是从确定性工程到概率编排的转变。我们正在从仅仅了解事物的系统转向实际执行事物的积极执行引擎。当应用跨越这条界限并在现实世界中采取行动时,准确性的重要性会发生彻底改变。

大语言模型 (LLM) 了解逻辑,但其内部记忆是历史快照。例如,如果智能体管理供应链并错误地确认供应商的可用性或道路路线,您将面临燃油浪费、未达到服务等级协议 (SLA) 以及真正的业务中断。在多智能体架构中,您将面临级联幻觉问题。如果链中的一个智能体产生幻觉并将错误数据传递给第二个智能体,整个系统就会开始基于谎言做出现实世界的承诺。没有真相的自主性会成为巨大的责任。

接地要求智能体超出其训练权重。通过强制 AI 提取可验证的实时事实(例如地点数据和路线数据),您可以为智能体提供实时耳目,将统计猜测转化为知情的运营决策。

为什么选择 MCP

Model Context Protocol (MCP) 是一种开放标准,旨在使工具和数据集成即插即用。

过去,将 AI 模型连接到外部 API 需要编写严格的自定义封装容器。您必须手动处理每项功能的格式设置、错误解析和工具调用转换。

MCP 标准化了此集成层。通过实现 MCP 客户端,您的应用可以通过统一协议动态发现和执行服务器提供的工具。 这使开发者的重点从编写重复的 API 集成逻辑转向设计高级智能体网络。

Google Maps Grounding Lite MCP

Google Maps Grounding Lite MCP 是一种完全托管的 Google 托管 MCP 服务器,可直接集成到任何兼容的智能体框架中。

目前,该服务器提供三种用于接地的核心工具:

  • 搜索地点:请求有关地点的相关信息,并获取 AI 生成的地点数据摘要,以及摘要中包含的每个地点的地点 ID、纬度和经度坐标以及 Google 地图链接。您可以将返回的地点 ID 以及纬度和经度坐标与其他 Google Maps Platform API 搭配使用,以在地图上显示地点。
  • 查询天气:请求有关天气的信息,并返回当前状况、每小时预报和每日预报。
  • 计算路线:请求有关两个地点之间的驾车或步行路线的信息,并返回路线距离和时长信息。

如需访问该服务,您可以使用 API 密钥或 OAuth。Google Maps Platform 提供免费的 演示 API 密钥,专门用于帮助开发者立即开始原型设计。

地图接地 MCP 架构
Maps Grounding MCP 架构

集成 Maps Grounding MCP 的最佳实践

为了最大限度地提高数据的相关性并消除结构性幻觉,请围绕以下核心策略来锚定智能体的系统说明: * 明确具体:指示智能体使用精确位置。“纽约中央公园”比“纽约”产生的结果更好,就像“法国巴黎”可以避免与德克萨斯州巴黎混淆一样。

  • 分解通用查询:对于“约会之夜创意”等模糊请求,提示智能体将任务分解为特定的子搜索,例如“浪漫餐厅”“电影院”或“鸡尾酒吧”。

  • 先发现,后探索:先进行广泛的发现搜索(例如“周日营业且入口无障碍的日式餐厅”)。向用户呈现选项,然后运行后续查询以提取特定详细信息,例如所选场所的电话号码。

  • 绝不产生地点 ID 幻觉:地点 ID 是 Google Maps Platform 服务之间的关键连接组织。确保您的智能体知道它必须仅使用 search_places 工具明确返回的地点 ID,而不是尝试生成自己的地点 ID。

使用 Google ADK 实现旅行规划智能体

本部分介绍了如何使用 Google 智能体开发套件 (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 网页界面,请在 travel-concierge-google-maps-mcp 项目目录中运行以下命令:

adk web

在界面中进行交互

  • 在浏览器中加载 http://127.0.0.1:8000 处的界面
  • 尝试以下提示:
    • “我周六会在旧金山。请为我规划一日游。”
    • “查找金门公园附近的咖啡馆,并向我显示菜单亮点。”
    • “获取从 GooglePlex 到 SFO 的路线。”

当智能体收到提示时,规划器会评估用户的意图。 它会识别对空间和天气数据的需求,并使用 MCP 服务器自主触发 lookup_weather、search_places 和 compute_routes 工具。然后,智能体会为用户合成基于事实的行程。

总结

向智能体 AI 的转变正在物流、旅游和零售领域释放全新的功能。不过,真正的自主性需要坚如磐石的真相基础。

通过将 Model Context Protocol 与 Google Maps Grounding Lite 结合使用,您可以消除自定义 API 集成的摩擦,并为智能体提供所需的实时耳目。将模型锚定在实时空间数据中可确保它们根据当前现实世界中发生的情况做出运营决策,而不是根据训练数据中的冻结快照。

后续操作

主要作者:

Teresa Qin | Google Maps Platform DevX 工程师