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

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

本文档详细介绍了如何通过使用 Google 地图中可信的地理空间数据来接地 AI 代理,从而弥合静态推理与动态现实之间的差距。您将了解空间接地对于现实世界任务的重要性、Model Context Protocol (MCP) 如何简化工具集成,以及如何使用 Google 地图 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 架构
地图接地 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 Web 界面,请在 travel-concierge-google-maps-mcp 项目目录中运行以下命令:

adk web

在界面中互动

  • 在浏览器中加载 http://127.0.0.1:8000 处的界面
  • 不妨试试以下提示:
    • “我周六会在旧金山。帮我规划一日游。”
    • “查找金门公园附近的咖啡店,并显示菜单亮点。”
    • “Get directions from GooglePlex to SFO.”

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

总结

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

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

后续操作

主要作者:

Teresa Qin | Google Maps 平台 DevX 工程师