Skip to main content
Glama
jagan-shanmugam

OpenStreetMap MCP Server

get_route_directions

Calculate route directions between two geographic points using OpenStreetMap data. Provides turn-by-turn instructions, geometry, and transportation options for cars, bikes, or walking.

Instructions

Calculate detailed route directions between two geographic points.

This tool provides comprehensive routing information between two locations using OpenStreetMap/OSRM. The output can be minimized using the steps, overview, and annotations parameters to reduce the response size.

Args: from_latitude: Starting point latitude (decimal degrees) from_longitude: Starting point longitude (decimal degrees) to_latitude: Destination latitude (decimal degrees) to_longitude: Destination longitude (decimal degrees) ctx: Context (provided internally by MCP) mode: Transportation mode ("car", "bike", "foot") steps: Turn-by-turn instructions (True/False, Default: False) overview: Geometry output ("full", "simplified", "false"; Default: "simplified") annotations: Additional segment info (True/False, Default: False)

Returns: Dictionary with routing information (summary, directions, geometry, waypoints)

Example: { "from_latitude": 51.3334193, "from_longitude": 9.4540423, "to_latitude": 51.3295516, "to_longitude": 9.4576721, "mode": "car", "steps": false, "overview": "simplified", "annotations": false }

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
from_latitudeYes
from_longitudeYes
to_latitudeYes
to_longitudeYes
modeNocar
stepsNo
overviewNosimplified
annotationsNo

Implementation Reference

  • The main @mcp.tool()-decorated async handler function implementing the 'get_route_directions' tool. Validates input mode, calls OSMClient.get_route to fetch OSRM route data, processes routes to extract summary, turn-by-turn directions, geometry, and waypoints.
    @mcp.tool()
    async def get_route_directions(
        from_latitude: float,
        from_longitude: float,
        to_latitude: float,
        to_longitude: float,
        ctx: Context,
        mode: str = "car",
        steps: bool = False,
        overview: str = "simplified",
        annotations: bool = False
    ) -> Dict[str, Any]:
        """
        Calculate detailed route directions between two geographic points.
        
        This tool provides comprehensive routing information between two locations using OpenStreetMap/OSRM.
        The output can be minimized using the steps, overview, and annotations parameters to reduce the response size.
        
        Args:
            from_latitude: Starting point latitude (decimal degrees)
            from_longitude: Starting point longitude (decimal degrees)
            to_latitude: Destination latitude (decimal degrees)
            to_longitude: Destination longitude (decimal degrees)
            ctx: Context (provided internally by MCP)
            mode: Transportation mode ("car", "bike", "foot")
            steps: Turn-by-turn instructions (True/False, Default: False)
            overview: Geometry output ("full", "simplified", "false"; Default: "simplified")
            annotations: Additional segment info (True/False, Default: False)
        
        Returns:
            Dictionary with routing information (summary, directions, geometry, waypoints)
    
        Example:
            {
              "from_latitude": 51.3334193,
              "from_longitude": 9.4540423,
              "to_latitude": 51.3295516,
              "to_longitude": 9.4576721,
              "mode": "car",
              "steps": false,
              "overview": "simplified",
              "annotations": false
            }
        """
        osm_client = ctx.request_context.lifespan_context.osm_client
        
        # Validate transportation mode
        valid_modes = ["car", "bike", "foot"]
        if mode not in valid_modes:
            ctx.warning(f"Invalid mode '{mode}'. Using 'car' instead.")
            mode = "car"
        
        ctx.info(f"Calculating {mode} route from ({from_latitude}, {from_longitude}) to ({to_latitude}, {to_longitude})")
        
        # Get route from OSRM
        route_data = await osm_client.get_route(
            from_latitude, from_longitude,
            to_latitude, to_longitude,
            mode,
            steps=steps,
            overview=overview,
            annotations=annotations
        )
        
        # Process and simplify the response
        if "routes" in route_data and len(route_data["routes"]) > 0:
            route = route_data["routes"][0]
            
            # Extract turn-by-turn directions
            steps_list = []
            if "legs" in route:
                for leg in route["legs"]:
                    for step in leg.get("steps", []):
                        steps_list.append({
                            "instruction": step.get("maneuver", {}).get("instruction", ""),
                            "distance": step.get("distance"),
                            "duration": step.get("duration"),
                            "name": step.get("name", "")
                        })
            
            return {
                "summary": {
                    "distance": route.get("distance"),  # meters
                    "duration": route.get("duration"),  # seconds
                    "mode": mode
                },
                "directions": steps_list,
                "geometry": route.get("geometry"),
                "waypoints": route_data.get("waypoints", [])
            }
        else:
            raise Exception("No route found")
  • Supporting helper method in OSMClient class that queries the OSRM routing API to retrieve raw route data between coordinates, which is then processed by the main handler.
    async def get_route(self, 
                         from_lat: float, 
                         from_lon: float, 
                         to_lat: float, 
                         to_lon: float,
                         mode: str = "car",
                         steps: bool = False,
                         overview: str = "overview",
                         annotations: bool = True) -> Dict:
        """Get routing information between two points"""
        if not self.session:
            raise RuntimeError("OSM client not connected")
        
        # Use OSRM for routing
        osrm_url = f"http://router.project-osrm.org/route/v1/{mode}/{from_lon},{from_lat};{to_lon},{to_lat}"
        params = {
            "overview": overview,
            "geometries": "geojson",
            "steps": str(steps).lower(),
            "annotations": str(annotations).lower()
        }
        
        async with self.session.get(osrm_url, params=params) as response:
            if response.status == 200:
                return await response.json()
            else:
                raise Exception(f"Failed to get route: {response.status}")
Behavior3/5

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

With no annotations provided, the description carries full burden. It discloses that the tool provides comprehensive routing information and mentions output minimization capabilities, but doesn't cover rate limits, authentication needs, error conditions, or performance characteristics. It adds some behavioral context but leaves significant gaps.

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

Conciseness4/5

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

The description is well-structured with purpose statement, behavioral context, parameter documentation, return value explanation, and example. While comprehensive, some sentences could be more concise. The front-loaded purpose statement is effective.

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

Completeness4/5

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

Given the complexity (8 parameters, routing tool) with no annotations and no output schema, the description does well by explaining parameters thoroughly, describing return values, and providing an example. However, it could better address behavioral aspects like error handling or performance expectations.

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

Parameters5/5

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

With 0% schema description coverage, the description fully compensates by providing detailed parameter explanations including data types, formats, default values, and usage context. Each parameter is clearly documented with meaningful descriptions beyond what the bare schema provides.

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

Purpose5/5

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

The description clearly states the tool's purpose with specific verbs ('calculate detailed route directions') and resources ('between two geographic points'), and distinguishes it from siblings by specifying it uses OpenStreetMap/OSRM for routing. This is precise and differentiates from tools like analyze_commute or find_nearby_places.

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

Usage Guidelines3/5

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

The description implies usage context by mentioning routing between two points and output minimization, but lacks explicit guidance on when to use this versus alternatives like analyze_commute or geocode_address. No when-not-to-use scenarios or prerequisites are provided.

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/jagan-shanmugam/open-streetmap-mcp'

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