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;
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. While 'Get navigation route' implies a read-only operation, it doesn't disclose important behavioral traits like authentication requirements, rate limits, response format, error conditions, or whether this is a real-time vs. cached service. The description is minimal and lacks operational context.

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 - a single sentence that gets straight to the point with zero wasted words. It's front-loaded with the core functionality and uses clear, direct language without unnecessary elaboration.

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 tool with no annotations and no output schema, the description is insufficiently complete. It doesn't explain what the tool returns (route geometry? distance? duration? turn-by-turn instructions?), doesn't mention error conditions or limitations, and provides no context about the Mapbox service it interacts with. The agent would have significant gaps in understanding how to properly use this tool.

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?

The schema description coverage is 100%, with both parameters well-documented in the schema itself. The description doesn't add any meaningful parameter semantics beyond what's already in the schema - it mentions 'between two points' which implies the coordinates array should contain exactly two coordinate objects, but this constraint isn't explicitly stated in either the description or schema.

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 distinguish 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. There's no mention of sibling tools like 'mapbox_directions_by_places' or 'mapbox_matrix', nor any context about when coordinate-based routing is preferred over place-based routing or matrix calculations.

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

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/AidenYangX/mapbox-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server