Skip to main content
Glama
jagan-shanmugam

OpenStreetMap MCP Server

geocode_address

Convert addresses or place names to geographic coordinates with location details for mapping, navigation, and geospatial analysis.

Instructions

Convert an address or place name to geographic coordinates with detailed location information.

This tool takes a text description of a location (such as an address, landmark name, or place of interest) and returns its precise geographic coordinates along with rich metadata. The results can be used for mapping, navigation, location-based analysis, and as input to other geospatial tools.

Args: address: The address, place name, landmark, or description to geocode (e.g., "Empire State Building", "123 Main St, Springfield", "Golden Gate Park, San Francisco")

Returns: List of matching locations with: - Geographic coordinates (latitude/longitude) - Formatted address - Administrative boundaries (city, state, country) - OSM type and ID - Bounding box (if applicable) - Importance ranking

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
addressYes

Implementation Reference

  • The primary handler function for the 'geocode_address' tool. It is registered via the @mcp.tool() decorator and implements the core logic by calling the OSMClient.geocode method, enhancing results with coordinates, and returning the geocoded locations.
    @mcp.tool()
    async def geocode_address(address: str, ctx: Context) -> List[Dict]:
        """
        Convert an address or place name to geographic coordinates with detailed location information.
        
        This tool takes a text description of a location (such as an address, landmark name, or
        place of interest) and returns its precise geographic coordinates along with rich metadata.
        The results can be used for mapping, navigation, location-based analysis, and as input to
        other geospatial tools.
        
        Args:
            address: The address, place name, landmark, or description to geocode (e.g., "Empire State Building", 
                    "123 Main St, Springfield", "Golden Gate Park, San Francisco")
            
        Returns:
            List of matching locations with:
            - Geographic coordinates (latitude/longitude)
            - Formatted address
            - Administrative boundaries (city, state, country)
            - OSM type and ID
            - Bounding box (if applicable)
            - Importance ranking
        """
        osm_client = ctx.request_context.lifespan_context.osm_client
        results = await osm_client.geocode(address)
        
        # Enhance results with additional context
        for result in results:
            if "lat" in result and "lon" in result:
                result["coordinates"] = {
                    "latitude": float(result["lat"]),
                    "longitude": float(result["lon"])
                }
        
        return results
  • The supporting 'geocode' method in the OSMClient class that performs the actual HTTP request to Nominatim API for geocoding the address.
    async def geocode(self, query: str) -> List[Dict]:
        """Geocode an address or place name"""
        if not self.session:
            raise RuntimeError("OSM client not connected")
        
        nominatim_url = "https://nominatim.openstreetmap.org/search"
        async with self.session.get(
            nominatim_url,
            params={
                "q": query,
                "format": "json",
                "limit": 5
            },
            headers={"User-Agent": "OSM-MCP-Server/1.0"}
        ) as response:
            if response.status == 200:
                return await response.json()
            else:
                raise Exception(f"Failed to geocode '{query}': {response.status}")
  • The OSMClient class that manages the HTTP session and provides the geocoding functionality used by the tool handler.
    class OSMClient:
        def __init__(self, base_url="https://api.openstreetmap.org/api/0.6"):
            self.base_url = base_url
            self.session = None
            self.cache = {}  # Simple in-memory cache
        
        async def connect(self):
            self.session = aiohttp.ClientSession()
            
        async def disconnect(self):
            if self.session:
                await self.session.close()
  • The @mcp.tool() decorator registers the geocode_address function as an MCP tool.
    @mcp.tool()

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

A4.2/5.0
Behavior3/5

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

With no annotations, the description carries the full burden. It discloses the return structure (list of matches, coordinates, formatted address, admin boundaries, OSM type/id, bounding box, importance ranking), which gives useful behavioral insight. However, it does not mention potential ambiguity (e.g., multiple matches), error conditions, or whether the operation is read-only (though implied). More disclosure would improve it.

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 a clear summary, an explanatory paragraph, and explicit Args/Returns sections. It is slightly longer than necessary for a single-parameter tool, but every sentence provides useful information. It is front-loaded with the core purpose, so appropriate.

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 there is no output schema, the description appropriately details the return format. It covers the key aspects needed to use the tool: what input to provide, what output to expect, and the structure of results. It does not cover edge cases like empty results or API limitations, but for a geocoding tool this is sufficient.

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?

The schema provides only a bare 'address' string with 0% coverage. The description compensates fully by explaining the parameter: 'The address, place name, landmark, or description to geocode' and offers concrete examples. This adds significant semantic meaning beyond the schema, making the tool easy to invoke correctly.

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 function: 'Convert an address or place name to geographic coordinates with detailed location information.' This uses a specific verb and resource, and the scope is unambiguous. It implicitly distinguishes from sibling tool reverse_geocode by specifying forward geocoding.

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

Usage Guidelines4/5

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

The description provides usage context: 'The results can be used for mapping, navigation, location-based analysis, and as input to other geospatial tools.' This implies when it is useful, though it does not explicitly mention when not to use it or alternative tools. Still, the purpose is clear enough for an agent to select it for address-to-coordinates tasks.

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