Amazon Location Service · 2026-11-16 · Location Service arc

Amazon Location Service for MCP Server Teams: The Four-Layer Geospatial Stack from Place Search to Automatic Geofence Notifications

MCP servers increasingly need to answer geospatial questions: "where is this address?", "how long will it take my delivery driver to get there?", "has the fleet vehicle left the authorized service zone?" Amazon Location Service covers all four of these patterns within a single AWS account boundary — no external API keys, no separate billing relationship, no data leaving your VPC. But the SDK surface has non-obvious conventions, and the wrong assumption about coordinate order alone will make every route point into the ocean. This guide synthesizes the full Location Service SDK into a four-layer playbook: place search and geocoding, route calculation, geofencing, and device tracking — with the five production gotchas that cause silent failures on first deployment.

TL;DR — four layers, five gotchas

Layer SDK surface The production gotcha
1 — Place search SearchPlaceIndexForTextCommand, SearchPlaceIndexForPositionCommand, GetPlaceCommand All coordinates are [longitude, latitude] — longitude index 0, latitude index 1. The reverse of most APIs.
1b — Country filtering FilterCountries in SearchPlaceIndexForTextCommand FilterCountries uses ISO 3166-1 alpha-3 three-letter codes ("USA" not "US") — alpha-2 returns a validation error.
2 — Routing CalculateRouteCommand, CalculateRouteMatrixCommand Route matrix cells can individually fail — always check per-cell Error property, not just the top-level response status.
3 — Geofencing PutGeofenceCommand, BatchEvaluateGeofencesCommand BatchEvaluateGeofencesCommand response only returns Errors — entry/exit events are emitted via EventBridge (aws.geo source), not in the API response body.
4 — Device tracking BatchUpdateDevicePositionCommand, GetDevicePositionHistoryCommand SampleTime must be monotonically increasing per device — out-of-order updates are silently discarded. DistanceBased filtering also skips any update within 30 m of the last stored position.

Why geospatial context belongs in MCP servers

LLM agents receive natural-language queries that frequently reference physical locations. A query like "find coffee shops near the convention center and tell me the fastest way to get there" requires three distinct geospatial operations: geocode "convention center" to coordinates, run a nearby place search, and calculate a walking or driving route from the user's current position. Without a geospatial layer, the MCP server must either refuse, hallucinate coordinates, or call an external API (Google Maps, Mapbox) with a separate API key and billing account.

Amazon Location Service solves this in-account. It provides four named, persistent resource types — place indexes, route calculators, geofence collections, and trackers — that you create once at deploy time and reference by name in every subsequent SDK call. All four authenticate via IAM. All four share the same coordinate convention: GeoJSON, where every position is [longitude, latitude].

The SDK package is @aws-sdk/client-location. Install it once; it covers all four resource types. The IAM action prefix is geo: — not location:. This is the second most common first-contact error after the coordinate order.

npm install @aws-sdk/client-location

Layer 1 — Place search and geocoding

Place search is the entry point for most geospatial MCP tools. An agent calls your tool with a free-text location query; your MCP server resolves it to structured coordinates and address components via SearchPlaceIndexForTextCommand.

Creating a place index

A place index is a persistent named resource that specifies a data source. Create it once; subsequent search calls reference it by name. The data source is locked at creation time — you cannot change it. Create a new index to switch data sources.

import {
  LocationClient,
  CreatePlaceIndexCommand,
} from "@aws-sdk/client-location";

const location = new LocationClient({ region: "us-east-1" });

await location.send(new CreatePlaceIndexCommand({
  IndexName: "my-mcp-place-index",
  DataSource: "Esri",           // "Esri" | "HERE" | "Grab" | "Open"
  DataSourceConfiguration: {
    IntendedUse: "SingleUse",   // "SingleUse" (no caching) | "Storage" (can cache results)
  },
  Tags: { "mcp-server": "true" },
}));

Data source selection matters for coverage and cost. Esri and HERE both cover global addresses at $0.50 per 1,000 requests and have strong accuracy in North America and Europe respectively. Grab is required for accurate coverage in Southeast Asia (SG, MY, TH, ID, PH, VN). Open Data uses OpenStreetMap and is free but has weaker address accuracy and does not support IntendedUse: "Storage". For most MCP server use cases, start with Esri unless you have Southeast Asia traffic, in which case you need Grab.

Text-to-place search

import { SearchPlaceIndexForTextCommand } from "@aws-sdk/client-location";

const result = await location.send(new SearchPlaceIndexForTextCommand({
  IndexName: "my-mcp-place-index",
  Text: "Space Needle, Seattle",
  MaxResults: 5,
  Language: "en",
}));

for (const place of result.Results ?? []) {
  const { Label, Geometry, Municipality, Region, Country } = place.Place!;
  const [lon, lat] = Geometry!.Point!;   // [longitude, latitude] — longitude first
  console.log(Label, lat, lon);
}

Gotcha 1 — coordinate order: Geometry.Point is [longitude, latitude]. Longitude is index 0; latitude is index 1. This is GeoJSON convention and the reverse of most mapping APIs that use (lat, lon) tuples. Swapping the order does not throw an error — it places every coordinate in the wrong hemisphere, and the bug only surfaces when you check results on a map or notice routes heading to unexpected locations. Store coordinates correctly from the first SDK call; fix it later and you will also need to migrate all stored data.

Biasing and bounding searches

Use BiasPosition to rank results near a known coordinate, or FilterBBox to restrict results to a bounding box:

// Bias toward Seattle downtown
const nearbyResult = await location.send(new SearchPlaceIndexForTextCommand({
  IndexName: "my-mcp-place-index",
  Text: "coffee",
  BiasPosition: [-122.3321, 47.6062],  // [longitude, latitude]
  MaxResults: 10,
}));

// Or restrict to a bounding box: [westLon, southLat, eastLon, northLat]
const bboxResult = await location.send(new SearchPlaceIndexForTextCommand({
  IndexName: "my-mcp-place-index",
  Text: "hospital",
  FilterBBox: [-122.45, 47.55, -122.25, 47.70],
  MaxResults: 20,
}));

BiasPosition and FilterBBox are mutually exclusive. Use BiasPosition when you want nearby results but are willing to include further results; use FilterBBox when you need a hard geographic boundary.

Country filtering

Gotcha 2 — alpha-3 country codes: FilterCountries uses ISO 3166-1 alpha-3 codes — three-letter codes — not the two-letter alpha-2 codes used by most other APIs:

// Correct: three-letter alpha-3
const usResult = await location.send(new SearchPlaceIndexForTextCommand({
  IndexName: "my-mcp-place-index",
  Text: "Springfield",
  FilterCountries: ["USA"],  // "USA" not "US" — alpha-3
  MaxResults: 10,
}));

// Multi-country: North American NAFTA zone
const naResult = await location.send(new SearchPlaceIndexForTextCommand({
  IndexName: "my-mcp-place-index",
  Text: "Toronto",
  FilterCountries: ["USA", "CAN", "MEX"],  // alpha-3 codes
  MaxResults: 10,
}));

Passing "US" instead of "USA" returns a validation error rather than silently returning results for a different country. The error message is clear once you see it, but the code review path of "it's a US-only product, add a country filter" reliably produces this mistake the first time.

Reverse geocoding and place lookup

Reverse geocoding turns GPS coordinates into a human-readable address:

import { SearchPlaceIndexForPositionCommand } from "@aws-sdk/client-location";

const reverseResult = await location.send(new SearchPlaceIndexForPositionCommand({
  IndexName: "my-mcp-place-index",
  Position: [-122.3321, 47.6062],  // [longitude, latitude]
  MaxResults: 1,
  Language: "en",
}));

const topResult = reverseResult.Results?.[0];
if (topResult) {
  const { Label, Municipality, Region, PostalCode } = topResult.Place!;
  console.log("Address:", Label);
  console.log("City:", Municipality, "State:", Region, "ZIP:", PostalCode);
}

For MCP tool responses, return Label (the formatted full address string) and separately expose Municipality, Region, and PostalCode for structured downstream use by the agent. The first result is usually the most specific address match.

When a previous search result includes a PlaceId, use GetPlaceCommand to retrieve full details without a new search. Note that PlaceId values are data-source-specific and have limited lifetimes — use them within a session, but do not store them as stable long-term references in a database.

Layer 2 — Route calculation

Route calculators provide driving, truck, walking, and cycling directions and also support origin-destination matrices for logistics planning. Like place indexes, they are named persistent resources you create once and reference by name.

Creating a route calculator

import { CreateRouteCalculatorCommand } from "@aws-sdk/client-location";

await location.send(new CreateRouteCalculatorCommand({
  CalculatorName: "my-mcp-route-calculator",
  DataSource: "Esri",    // "Esri" | "HERE" | "Grab" (not "Open")
  Tags: { "mcp-server": "true" },
}));

Route calculators do not support the Open data source — only Esri, HERE, and Grab. Grab is limited to Southeast Asian AWS regions. For global routing, use Esri or HERE.

Basic route calculation

import {
  CalculateRouteCommand,
  TravelMode,
  DistanceUnit,
} from "@aws-sdk/client-location";

const route = await location.send(new CalculateRouteCommand({
  CalculatorName: "my-mcp-route-calculator",
  DeparturePosition: [-122.3321, 47.6062],    // [longitude, latitude]
  DestinationPosition: [-122.2015, 47.6101],
  TravelMode: TravelMode.CAR,
  DistanceUnit: DistanceUnit.KILOMETERS,
  IncludeLegGeometry: true,
}));

const summary = route.Summary!;
console.log("Distance:", summary.Distance, "km");
console.log("Duration:", Math.round(summary.DurationSeconds / 60), "minutes");

All positions are [longitude, latitude] — the same coordinate order as place search. Swapping the order places the route on the wrong continent without an error. TravelMode options are Car, Truck, Walking, and Bicycle (Bicycle requires HERE). The response gives Summary.Distance in the requested unit and Summary.DurationSeconds as a total. The Legs array breaks the journey into segments, each with its own distance, duration, and step-level turn directions.

Truck routing

For logistics MCP tools, use TravelMode.TRUCK with TruckModeOptions to route around height, weight, and hazmat restrictions. CarModeOptions and TruckModeOptions are mutually exclusive:

const truckRoute = await location.send(new CalculateRouteCommand({
  CalculatorName: "my-mcp-route-calculator",
  DeparturePosition: [-87.6298, 41.8781],  // Chicago
  DestinationPosition: [-90.1994, 38.6270], // St. Louis
  TravelMode: TravelMode.TRUCK,
  TruckModeOptions: {
    AvoidFerries: true,
    AvoidTolls: false,
    Dimensions: {
      Height: 4.1,     // meters
      Width: 2.4,
      Length: 16.8,
    },
    Weight: {
      Total: 36000,    // kg
      Unit: "Kilograms",
    },
  },
  DistanceUnit: DistanceUnit.KILOMETERS,
}));

Truck routing respects bridge height clearances, weight limits, and hazmat route restrictions based on the dimensions and weight you provide. For an MCP tool used by a logistics team, always pass TruckModeOptions with real vehicle specs — routing a 4.1 m-tall trailer over a 3.9 m bridge is an expensive mistake.

Traffic-aware routing

Provide a DepartureTime (ISO 8601 UTC string) to get time-of-day traffic-aware routing. Only supported with Esri and HERE data sources:

const rushHour = new Date();
rushHour.setDate(rushHour.getDate() + 1);
rushHour.setHours(8, 0, 0, 0);  // Tomorrow 8am local → UTC

const trafficRoute = await location.send(new CalculateRouteCommand({
  CalculatorName: "my-mcp-route-calculator",
  DeparturePosition: [-74.0060, 40.7128],   // NYC
  DestinationPosition: [-73.8787, 40.7549], // Queens
  TravelMode: TravelMode.CAR,
  DepartureTime: rushHour.toISOString(),
  DistanceUnit: DistanceUnit.KILOMETERS,
}));

Without DepartureTime, routing uses free-flow traffic conditions — optimal conditions that may underestimate real-world travel time by 30–50% during peak hours. For logistics planning tools, always supply DepartureTime so the agent gets realistic estimates rather than free-flow ideals.

Multi-stop routing with waypoints

Use WaypointPositions for multi-stop routes. Amazon Location Service supports up to 23 waypoints per route (departure + 23 waypoints + destination = 25 total positions). Waypoints are visited in the order provided — the API does not optimize the sequence:

const multiStopRoute = await location.send(new CalculateRouteCommand({
  CalculatorName: "my-mcp-route-calculator",
  DeparturePosition: [-122.3321, 47.6062],    // Seattle
  DestinationPosition: [-122.6587, 45.5231],  // Portland
  WaypointPositions: [
    [-122.6764, 45.5231],  // stop 1
    [-122.9007, 46.1430],  // stop 2
  ],
  TravelMode: TravelMode.CAR,
  IncludeLegGeometry: true,
}));

// Each Leg is one segment of the journey
for (let i = 0; i < multiStopRoute.Legs!.length; i++) {
  const leg = multiStopRoute.Legs![i];
  console.log(`Leg ${i + 1}: ${leg.Distance?.toFixed(1)} km, ${Math.round((leg.DurationSeconds ?? 0) / 60)} min`);
}

Origin-destination matrices for logistics

CalculateRouteMatrixCommand is the high-value operation for logistics MCP tools. It computes all pairwise travel times and distances between M origins and N destinations in a single API call:

import { CalculateRouteMatrixCommand } from "@aws-sdk/client-location";

const origins = [
  [-122.3321, 47.6062],  // Seattle warehouse
  [-87.6298, 41.8781],   // Chicago hub
];
const destinations = [
  [-118.2437, 34.0522],  // Los Angeles
  [-73.9857, 40.7484],   // New York
  [-95.3698, 29.7604],   // Houston
];

const matrix = await location.send(new CalculateRouteMatrixCommand({
  CalculatorName: "my-mcp-route-calculator",
  DeparturePositions: origins,
  DestinationPositions: destinations,
  TravelMode: TravelMode.TRUCK,
  DistanceUnit: DistanceUnit.KILOMETERS,
}));

// RouteMatrix[i][j] = route from origins[i] to destinations[j]
for (let i = 0; i < origins.length; i++) {
  for (let j = 0; j < destinations.length; j++) {
    const cell = matrix.RouteMatrix![i][j];
    if (cell.Error) {
      console.log(`Route ${i}→${j}: error (${cell.Error.Code})`);
    } else {
      console.log(
        `Route ${i}→${j}: ${cell.Distance?.toFixed(0)} km, ${Math.round((cell.DurationSeconds ?? 0) / 3600)} hr`
      );
    }
  }
}

Gotcha 3 — per-cell errors: The matrix operation can partially succeed. Some origin-destination pairs may be unreachable (islands without road connections, restricted zones, ferry-excluded routes with no road alternative) while others succeed. Each cell in the RouteMatrix can have an Error property — always check it on every cell before reading Distance or DurationSeconds. A 10×16 matrix call counts as 160 route requests at $0.75/1,000 — the total M×N count must be ≤ 160.

Layer 3 — Geofencing

Geofencing adds spatial triggers to MCP server architectures. Common patterns: a delivery confirmation MCP tool fires a "arrived at site" event when a driver enters a 100 m circle around a customer address; a zone-access MCP tool checks whether a user's current GPS position is inside an authorized perimeter before granting resource access; a fleet MCP server alerts a supervisor when a vehicle exits its assigned work zone.

Creating a geofence collection

import { CreateGeofenceCollectionCommand } from "@aws-sdk/client-location";

await location.send(new CreateGeofenceCollectionCommand({
  CollectionName: "my-mcp-geofences",
  Description: "Geofences for MCP server spatial triggers",
  Tags: { "mcp-server": "true" },
}));

Collections are free to create. You are charged per geofence evaluation request ($0.085 per 1,000 evaluations), not per stored geofence. A single collection can hold thousands of geofences.

Defining circle and polygon geofences

Circle geofences are the most common pattern for delivery, proximity, and point-of-interest triggers. Define them with a center point and a radius in meters:

import { PutGeofenceCommand } from "@aws-sdk/client-location";

await location.send(new PutGeofenceCommand({
  CollectionName: "my-mcp-geofences",
  GeofenceId: "warehouse-seattle",          // unique string ID within the collection
  Geometry: {
    Circle: {
      Center: [-122.3321, 47.6062],  // [longitude, latitude]
      Radius: 200,                   // meters
    },
  },
  GeofenceProperties: {              // optional key-value metadata
    "type": "warehouse",
    "region": "pacific-northwest",
  },
}));

Polygon geofences use GeoJSON linear ring syntax — a closed array of [longitude, latitude] positions where the first and last position must be identical. Amazon Location Service uses the right-hand rule: the outer ring must be counter-clockwise; holes must be clockwise:

await location.send(new PutGeofenceCommand({
  CollectionName: "my-mcp-geofences",
  GeofenceId: "downtown-seattle",
  Geometry: {
    Polygon: [
      [   // outer ring — counter-clockwise
        [-122.3600, 47.6000],
        [-122.3200, 47.6000],
        [-122.3200, 47.6200],
        [-122.3600, 47.6200],
        [-122.3600, 47.6000],  // closes the ring
      ],
    ],
  },
}));

If you submit a polygon with the wrong orientation, the service either corrects it silently or returns a validation error depending on the polygon complexity. After defining a polygon geofence, test it immediately by submitting a known point inside the boundary through BatchEvaluateGeofencesCommand and verifying the expected EventBridge event fires.

PutGeofenceCommand is an upsert — if the GeofenceId already exists, it replaces the geometry entirely. This makes batch geofence management idempotent but also means accidental re-runs in a deployment pipeline will silently update geometry. Use list-then-compare logic before bulk upsert operations on production collections.

Synchronous position evaluation and the BatchEvaluateGeofencesCommand gotcha

Gotcha 4 — BatchEvaluateGeofencesCommand returns only errors: This is the most confusing aspect of the geofencing API. BatchEvaluateGeofencesCommand does not return entry/exit events in the response body — it only returns Errors (devices that failed to process). The entry and exit events are emitted via EventBridge to the aws.geo source.

import { BatchEvaluateGeofencesCommand } from "@aws-sdk/client-location";

const evalResult = await location.send(new BatchEvaluateGeofencesCommand({
  CollectionName: "my-mcp-geofences",
  DevicePositionUpdates: [
    {
      DeviceId: "device-001",
      Position: [-122.3321, 47.6062],
      SampleTime: new Date(),
    },
  ],
}));

// This response ONLY contains errors — not the ENTER/EXIT results.
// If a device entered or exited a geofence, that information is in EventBridge.
for (const error of evalResult.Errors ?? []) {
  console.error("Eval error:", error.DeviceId, error.Error?.Code);
}

Many developers expect the response to contain something like [{ geofenceId: "warehouse-seattle", eventType: "ENTER", deviceId: "device-001" }]. It does not. If you need synchronous inside/outside determination, you have two options: (1) set up an EventBridge rule and consume events asynchronously, or (2) use the tracker-collection association pattern described below, which triggers geofence evaluation automatically on every position update and publishes to EventBridge.

EventBridge integration for entry/exit events

Associate a tracker with a geofence collection using AssociateTrackerConsumerCommand. After that, every BatchUpdateDevicePositionCommand call automatically evaluates the new position against all associated geofence collections and emits ENTER / EXIT events to EventBridge:

import { AssociateTrackerConsumerCommand } from "@aws-sdk/client-location";

await location.send(new AssociateTrackerConsumerCommand({
  TrackerName: "my-mcp-tracker",
  ConsumerArn: "arn:aws:geo:us-east-1:123456789012:geofence-collection/my-mcp-geofences",
}));

The EventBridge event structure for a geofence crossing:

{
  "source": "aws.geo",
  "detail-type": "Location Geofence Event",
  "detail": {
    "EventType": "ENTER",         // "ENTER" | "EXIT"
    "GeofenceId": "warehouse-seattle",
    "DeviceId": "device-001",
    "TrackerName": "my-mcp-tracker",
    "Position": [-122.3321, 47.6062],
    "SampleTime": "2026-11-16T10:30:00.000Z"
  }
}

Create an EventBridge rule matching source: ["aws.geo"] and detail-type: ["Location Geofence Event"]. Route ENTER events to a Lambda that records the delivery arrival, sends a Slack notification, or triggers a downstream MCP tool call. Route EXIT events to a different handler that resets the in-zone state for that device. GeofenceProperties that you attached to the geofence at creation time are not included in the EventBridge payload — look them up from your own metadata store using GeofenceId as the key.

Layer 4 — Device tracking

Device trackers store position history and serve as the source-of-truth for where a fleet of devices, vehicles, or users has been. MCP servers use trackers in two modes: ingestion mode (receiving GPS pings from client tool calls and writing them to the tracker) and query mode (answering "where is device X right now" and "show me truck-007's route for the last 2 hours").

Creating a tracker with position filtering

import {
  CreateTrackerCommand,
  PositionFiltering,
} from "@aws-sdk/client-location";

await location.send(new CreateTrackerCommand({
  TrackerName: "my-mcp-tracker",
  Description: "Device position tracker for MCP server fleet tools",
  PositionFiltering: PositionFiltering.TIME_BASED,
  Tags: { "mcp-server": "true" },
}));

PositionFiltering controls deduplication at ingest time:

Ingesting device positions

BatchUpdateDevicePositionCommand accepts up to 10 device updates per call:

import {
  BatchUpdateDevicePositionCommand,
  type DevicePositionUpdate,
} from "@aws-sdk/client-location";

const updates: DevicePositionUpdate[] = [
  {
    DeviceId: "truck-001",
    Position: [-122.3321, 47.6062],  // [longitude, latitude]
    SampleTime: new Date("2026-11-16T10:00:00Z"),
    PositionProperties: {
      "speed_kmh": "65",
      "heading": "northwest",
    },
    Accuracy: {
      Horizontal: 15,  // meters
    },
  },
  {
    DeviceId: "truck-002",
    Position: [-87.6298, 41.8781],
    SampleTime: new Date("2026-11-16T10:00:05Z"),
  },
];

const result = await location.send(new BatchUpdateDevicePositionCommand({
  TrackerName: "my-mcp-tracker",
  Updates: updates,
}));

for (const error of result.Errors ?? []) {
  console.error("Failed:", error.DeviceId, error.Error?.Code, error.Error?.Message);
}

Gotcha 5 — SampleTime monotonicity: SampleTime must be greater than or equal to the timestamp of the last stored position for each device. Out-of-order updates — which commonly occur when replaying historical data, retrying failed batches, or ingesting from multiple producers writing to the same device ID — are silently discarded. They appear in the Errors array rather than raising an exception, so a successful HTTP 200 response can still mean some updates were dropped. Always sort updates by SampleTime ascending before ingesting, and verify by reading back the latest position after a batch.

The DistanceBased filtering interaction is worth noting separately: even with correctly ordered timestamps, a parked vehicle sending position every 30 seconds will generate only one stored update per 30 m of movement. This is desirable for cost control — a vehicle parked for 2 hours sending 240 position updates at TimeBased storage incurs the same device-day charge as DistanceBased, but generates 240× more geofence evaluation charges if the tracker has associated collections. Set DistanceBased for fleet vehicles unless you need sub-30 m precision for entry/exit evaluation on small geofences.

Querying latest position

import { GetDevicePositionCommand } from "@aws-sdk/client-location";

const latest = await location.send(new GetDevicePositionCommand({
  TrackerName: "my-mcp-tracker",
  DeviceId: "truck-001",
}));

if (latest.Position) {
  const [lon, lat] = latest.Position;  // [longitude, latitude]
  const ageMs = Date.now() - (latest.SampleTime?.getTime() ?? 0);
  console.log(`Truck-001 at ${lat.toFixed(5)},${lon.toFixed(5)}, ${Math.round(ageMs / 60000)}m ago`);
}

ReceivedTime is when the server received the update; SampleTime is the GPS measurement timestamp you submitted. For detecting stale devices, compare SampleTime against the current time — a vehicle whose SampleTime is 30+ minutes old likely has a connectivity or hardware issue.

Position history

import { GetDevicePositionHistoryCommand } from "@aws-sdk/client-location";

const twoHoursAgo = new Date(Date.now() - 2 * 60 * 60 * 1000);

async function* deviceHistory(
  client: LocationClient,
  trackerName: string,
  deviceId: string,
  startTime: Date,
  endTime: Date,
) {
  let nextToken: string | undefined;
  do {
    const resp = await client.send(new GetDevicePositionHistoryCommand({
      TrackerName: trackerName,
      DeviceId: deviceId,
      StartTimeInclusive: startTime,
      EndTimeExclusive: endTime,
      MaxResults: 100,
      NextToken: nextToken,
    }));
    yield* resp.DevicePositions ?? [];
    nextToken = resp.NextToken;
  } while (nextToken);
}

for await (const pos of deviceHistory(location, "my-mcp-tracker", "truck-001", twoHoursAgo, new Date())) {
  const [lon, lat] = pos.Position!;
  console.log(pos.SampleTime?.toISOString(), lat.toFixed(5), lon.toFixed(5));
}

Default retention is 30 days. Without time range filters, the command returns the full 30-day history. For MCP tools reconstructing a route audit trail, always pass a narrow StartTimeInclusive / EndTimeExclusive window to bound response size. The paginated async generator pattern above is correct — do not load all positions into memory for large fleets or long windows.

Fleet overview with ListDevicePositionsCommand

import { ListDevicePositionsCommand } from "@aws-sdk/client-location";

async function* allDevicePositions(client: LocationClient, trackerName: string) {
  let nextToken: string | undefined;
  do {
    const resp = await client.send(new ListDevicePositionsCommand({
      TrackerName: trackerName,
      MaxResults: 100,
      NextToken: nextToken,
    }));
    yield* resp.Entries ?? [];
    nextToken = resp.NextToken;
  } while (nextToken);
}

for await (const device of allDevicePositions(location, "my-mcp-tracker")) {
  const [lon, lat] = device.Position!;
  const ageMin = Math.round((Date.now() - (device.SampleTime?.getTime() ?? 0)) / 60000);
  console.log(device.DeviceId, lat.toFixed(5), lon.toFixed(5), `${ageMin}m ago`);
}

This is the fleet overview operation — it returns the most recent position for every device in the tracker. Use it to build an MCP tool like list_fleet_positions() that returns current coordinates for all vehicles. For large fleets, this is significantly more efficient than issuing one GetDevicePositionCommand per device.

GDPR position data deletion

import { DeleteDevicePositionHistoryCommand } from "@aws-sdk/client-location";

await location.send(new DeleteDevicePositionHistoryCommand({
  TrackerName: "my-mcp-tracker",
  DeviceIds: ["truck-001", "truck-002"],  // up to 10 per call
}));

Device IDs in fleet tracking systems often map to named individuals (assigned drivers) or identified vehicles. Implement GDPR right-to-erasure support via DeleteDevicePositionHistoryCommand. Build this into your off-boarding workflow as a standard step — the 30-day retention clock restarts on the remaining devices after deletion.

The five production gotchas consolidated

# Gotcha What goes wrong Fix
1 Coordinate order Coordinates stored as [lat, lon] instead of [lon, lat]. Routes point to wrong continent. No validation error. Always destructure as const [lon, lat] = point. Document the convention in your codebase.
2 FilterCountries alpha-3 FilterCountries: ["US"] returns a validation error instead of filtering to the US. Use three-letter alpha-3 codes: "USA" not "US", "CAN" not "CA", "GBR" not "GB".
3 Route matrix per-cell errors Some cells fail (unreachable pairs) while others succeed. Reading cell.Distance on a failed cell returns undefined without an exception. Check if (cell.Error) on every cell before accessing distance and duration fields.
4 BatchEvaluateGeofencesCommand returns only errors Developer expects the API response to contain ENTER/EXIT events. It returns only errors. Entry/exit events are in EventBridge. Set up an EventBridge rule on source: ["aws.geo"] + detail-type: ["Location Geofence Event"]. Use tracker-collection association for automatic evaluation.
5 SampleTime monotonicity + DistanceBased filtering Out-of-order updates are silently discarded (appear in Errors array). DistanceBased filtering silently skips updates within 30 m. Sort updates by SampleTime ascending before ingesting. Use TimeBased if geofences <30 m radius need reliable triggering.

IAM policy for a full Location Service MCP server

All Location Service IAM actions use the geo: prefix — not location:. Scope resources to specific named indexes, calculators, collections, and trackers:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "PlaceSearch",
      "Effect": "Allow",
      "Action": [
        "geo:SearchPlaceIndexForText",
        "geo:SearchPlaceIndexForPosition",
        "geo:GetPlace"
      ],
      "Resource": "arn:aws:geo:us-east-1:123456789012:place-index/my-mcp-place-index"
    },
    {
      "Sid": "Routing",
      "Effect": "Allow",
      "Action": [
        "geo:CalculateRoute",
        "geo:CalculateRouteMatrix"
      ],
      "Resource": "arn:aws:geo:us-east-1:123456789012:route-calculator/my-mcp-route-calculator"
    },
    {
      "Sid": "GeofenceRead",
      "Effect": "Allow",
      "Action": [
        "geo:GetGeofence",
        "geo:ListGeofences",
        "geo:BatchEvaluateGeofences"
      ],
      "Resource": "arn:aws:geo:us-east-1:123456789012:geofence-collection/my-mcp-geofences"
    },
    {
      "Sid": "TrackerIngestionAndQuery",
      "Effect": "Allow",
      "Action": [
        "geo:BatchUpdateDevicePosition",
        "geo:GetDevicePosition",
        "geo:GetDevicePositionHistory",
        "geo:ListDevicePositions"
      ],
      "Resource": "arn:aws:geo:us-east-1:123456789012:tracker/my-mcp-tracker"
    }
  ]
}

Separate the write-intensive ingestion actions (geo:BatchUpdateDevicePosition, geo:PutGeofence) from the read-only query actions if your MCP server exposes both ingestion and query tools. IoT devices submitting GPS pings need only geo:BatchUpdateDevicePosition; LLM agents querying position history need only the read actions. Keeping these separate limits blast radius if either role is compromised.

Pricing summary

Operation Price Free tier
Place search / geocoding (Esri, HERE) $0.50 per 1,000 requests 10,000/month
Place search (Open Data) Free Unlimited
Route calculation $0.75 per 1,000 requests (single route or matrix cell) 10,000/month
Geofence evaluation $0.085 per 1,000 evaluations 100,000/month
Device tracking $0.085 per device per day 100 device-days/month

For a fleet of 20 vehicles tracked daily, tracking cost is 20 × 30 days × $0.085 = $51/month minus the 100 free device-days = ~$42.65/month. With DistanceBased filtering and 15-minute position updates, geofence evaluation adds approximately $0.085 × (20 vehicles × 96 updates/day × 30 days) / 1000 = ~$5/month. Total: around $48/month for a 20-vehicle fleet with geofencing — competitive with any commercial fleet tracking API at this precision level. Monitor AWS/Location CloudWatch metrics (SearchRequests, RouteRequests, GeofenceEvaluations, DeviceDays) and set billing alarms before enabling high-frequency tracking.

Connecting geospatial context to AliveMCP monitoring

An MCP server wiring Amazon Location Service into production has the same operational blind spots as any other MCP endpoint: if the server goes down, the geospatial tools become unavailable without warning. LLM agents that rely on route calculation or geofence checks will fail silently — or surface confusing errors to users. AliveMCP monitors your MCP server's uptime every 60 seconds and sends alerts via Slack or webhook before your users discover the outage. For MCP servers with real-time delivery tracking or zone-access enforcement, the cost of undetected downtime is higher than average — a monitored endpoint is a prerequisite for taking geospatial tools to production.