Skip to main content
Glama

mapbox_directions

Calculate navigation routes between locations using driving, walking, cycling, or traffic-aware driving modes to plan journeys efficiently.

Instructions

Get navigation route between two points

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
coordinatesYesArray of coordinates
profileNoNavigation modedriving-traffic

Implementation Reference

  • Main handler function that executes the Mapbox Directions API call. Takes coordinates and profile, constructs the API URL, handles errors, and returns formatted route information including distance, duration, and step-by-step instructions.
    export async function handleDirections(
      coordinates: z.infer<typeof CoordinatesSchema>,
      profile: string = "driving"
    ) {
      const coordinatesString = coordinates
        .map((coord) => `${coord.longitude},${coord.latitude}`)
        .join(";");
    
      const url = new URL(
        `https://api.mapbox.com/directions/v5/mapbox/${profile}/${coordinatesString}`
      );
      url.searchParams.append("access_token", MAPBOX_ACCESS_TOKEN);
      url.searchParams.append("geometries", "geojson");
    
      try {
        const response = await fetch(url.toString());
    
        // Handle Server Error (HTTP Status Code >= 500)
        if (response.status >= 500) {
          return {
            content: [
              {
                type: "text",
                text: `Mapbox Server Error: HTTP ${response.status}`,
              },
            ],
            isError: true,
          };
        }
    
        const data = (await response.json()) as MapboxDirectionsResponse;
    
        // Handle Business Logic Error (HTTP Status Code < 500)
        if (response.status < 500 && data.code !== "Ok") {
          return {
            content: [
              {
                type: "text",
                text: data.message || `Route Planning Failed: ${data.code}`,
              },
            ],
            isError: true,
          };
        }
    
        // Success Case
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify({
                routes: data.routes.map((route) => ({
                  distance: route.distance,
                  duration: route.duration,
                  steps: route.legs[0].steps.map((step) => ({
                    instruction: step.maneuver.instruction,
                    distance: step.distance,
                    duration: step.duration,
                  })),
                })),
              }),
            },
          ],
          isError: false,
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `Request Failed: ${
                error instanceof Error ? error.message : String(error)
              }`,
            },
          ],
          isError: true,
        };
      }
    }
  • Tool definition schema for MCP registration. Defines the tool name 'mapbox_directions', description, and input schema with coordinates array and profile enum (driving-traffic, driving, walking, cycling).
    export const DIRECTIONS_TOOL: Tool = {
      name: "mapbox_directions",
      description: "Get navigation route between two points",
      inputSchema: {
        type: "object",
        properties: {
          coordinates: {
            type: "array",
            items: {
              type: "object",
              properties: {
                longitude: {
                  type: "number",
                  description: "Longitude",
                  minimum: -180,
                  maximum: 180,
                },
                latitude: {
                  type: "number",
                  description: "Latitude",
                  minimum: -90,
                  maximum: 90,
                },
              },
              required: ["longitude", "latitude"],
            },
            description: "Array of coordinates",
          },
          profile: {
            type: "string",
            description: "Navigation mode",
            enum: ["driving-traffic", "driving", "walking", "cycling"],
            default: "driving-traffic",
          },
        },
        required: ["coordinates"],
      },
    };
  • Zod validation schemas for direction arguments. Defines CoordinateSchema (longitude/latitude), CoordinatesSchema (array of at least 2 coordinates), and DirectionsArgsSchema for parsing and validating input.
    export const CoordinateSchema = z.object({
      longitude: z.number().describe("Longitude"),
      latitude: z.number().describe("Latitude"),
    });
    
    export const CoordinatesSchema = z
      .array(CoordinateSchema)
      .min(2)
      .describe("Array of coordinates");
    
    // Directions Arguments Schema
    export const DirectionsArgsSchema = z.object({
      coordinates: CoordinatesSchema,
      profile: z
        .enum(["driving-traffic", "driving", "walking", "cycling"])
        .default("driving"),
    });
  • NavigationHandler class that registers the tool and routes requests. Constructor adds 'mapbox_directions' to the tools set, and the handle method uses a switch statement to parse arguments and call the handleDirections function.
    export class NavigationHandler extends BaseHandler {
      constructor() {
        super();
        this.tools.add("mapbox_directions");
        this.tools.add("mapbox_directions_by_places");
        this.tools.add("mapbox_matrix");
        this.tools.add("mapbox_matrix_by_places");
        this.toolDefinitions.push(DIRECTIONS_TOOL);
        this.toolDefinitions.push(DIRECTIONS_BY_PLACES_TOOL);
        this.toolDefinitions.push(MATRIX_TOOL);
        this.toolDefinitions.push(MATRIX_BY_PLACES_TOOL);
      }
    
      async handle({ name, args }: { name: string; args: any }) {
        switch (name) {
          case "mapbox_directions": {
            const { coordinates, profile } = DirectionsArgsSchema.parse(args);
            return await handleDirections(coordinates, profile);
          }
  • TypeScript interface for Mapbox Directions API response. Defines the complete response structure including routes array with legs, steps, maneuvers, distance, duration, and waypoints.
    export interface MapboxDirectionsResponse {
      code: string;
      message?: string;
      routes: Array<{
        geometry: string;
        distance: number;
        duration: number;
        weight: number;
        weight_name: string;
        legs: Array<{
          summary: string;
          distance: number;
          duration: number;
          weight: number;
          steps: Array<{
            distance: number;
            duration: number;
            geometry: string;
            mode: string;
            driving_side: string;
            weight: number;
            name: string;
            maneuver: {
              location: [number, number];
              type: string;
              modifier?: string;
              bearing_before: number;
              bearing_after: number;
              instruction: string;
            };
            intersections: Array<{
              location: [number, number];
              bearings: number[];
              entry: boolean[];
              in?: number;
              out?: number;
            }>;
          }>;
        }>;
        weight_typical?: number;
      }>;
      waypoints: Array<{
        name: string;
        location: [number, number];
      }>;
      uuid: string;
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observedv1.0.0

TDQS

C2.9/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. While 'Get navigation route' implies a read-only operation, it doesn't address authentication requirements, rate limits, error conditions, response format, or whether this is a real-time vs. cached service. The description provides minimal behavioral context beyond the basic operation.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise at just 5 words, front-loading the core purpose without any wasted language. Every word earns its place in communicating the essential function.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a navigation API tool with no annotations and no output schema, the description is insufficient. It doesn't explain what a 'navigation route' includes (distance, duration, steps, geometry), error handling, authentication needs, or how results differ from sibling tools. The minimal description leaves too many contextual gaps for effective agent use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 100% schema description coverage, the schema already documents both parameters thoroughly. The description adds no additional parameter semantics beyond what's in the schema - it doesn't explain coordinate ordering (origin to destination), minimum/maximum points, or practical usage of the profile parameter. This meets the baseline for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb ('Get') and resource ('navigation route between two points'), making the purpose immediately understandable. However, it doesn't differentiate this tool from its sibling 'mapbox_directions_by_places', which likely serves a similar purpose with different input parameters.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. With sibling tools like 'mapbox_directions_by_places', 'mapbox_geocoding', and 'mapbox_matrix' available, there's no indication of when this coordinate-based directions tool is preferred over place-based or matrix alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.