Skip to main content
Glama
jagan-shanmugam

OpenStreetMap MCP Server

search_category

Find specific types of places like restaurants, schools, or parks within a defined geographic area using OpenStreetMap data.

Instructions

Search for specific types of places within a defined geographic area.

This tool allows targeted searches for places matching specific categories within a rectangular geographic region. It's particularly useful for filtering places by type (restaurants, schools, parks, etc.) within a neighborhood or city district. Results include complete location details and metadata about each matching place.

Args: category: Main OSM category to search for (e.g., "amenity", "shop", "tourism", "building") min_latitude: Southern boundary of search area (decimal degrees) min_longitude: Western boundary of search area (decimal degrees) max_latitude: Northern boundary of search area (decimal degrees) max_longitude: Eastern boundary of search area (decimal degrees) subcategories: Optional list of specific subcategories to filter by (e.g., ["restaurant", "cafe"])

Returns: Structured results including: - Query parameters - Count of matching places - List of matching places with coordinates, names, and metadata

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
categoryYes
min_latitudeYes
min_longitudeYes
max_latitudeYes
max_longitudeYes
subcategoriesNo

Implementation Reference

  • The main execution logic for the 'search_category' MCP tool. It constructs a bounding box from input coordinates, calls the helper method to query OSM features, processes the results to extract coordinates and metadata, and returns a structured response with query details, results list, and count.
    async def search_category(
        category: str,
        min_latitude: float,
        min_longitude: float,
        max_latitude: float,
        max_longitude: float,
        ctx: Context,
        subcategories: List[str] = None
    ) -> Dict[str, Any]:
        """
        Search for specific types of places within a defined geographic area.
        
        This tool allows targeted searches for places matching specific categories within
        a rectangular geographic region. It's particularly useful for filtering places by type
        (restaurants, schools, parks, etc.) within a neighborhood or city district. Results include
        complete location details and metadata about each matching place.
        
        Args:
            category: Main OSM category to search for (e.g., "amenity", "shop", "tourism", "building")
            min_latitude: Southern boundary of search area (decimal degrees)
            min_longitude: Western boundary of search area (decimal degrees)
            max_latitude: Northern boundary of search area (decimal degrees)
            max_longitude: Eastern boundary of search area (decimal degrees)
            subcategories: Optional list of specific subcategories to filter by (e.g., ["restaurant", "cafe"])
            
        Returns:
            Structured results including:
            - Query parameters
            - Count of matching places
            - List of matching places with coordinates, names, and metadata
        """
        osm_client = ctx.request_context.lifespan_context.osm_client
        
        bbox = (min_longitude, min_latitude, max_longitude, max_latitude)
        
        ctx.info(f"Searching for {category} in bounding box")
        features = await osm_client.search_features_by_category(bbox, category, subcategories)
        
        # Process results
        results = []
        for feature in features:
            tags = feature.get("tags", {})
            
            # Get coordinates based on feature type
            coords = {}
            if feature.get("type") == "node":
                coords = {
                    "latitude": feature.get("lat"),
                    "longitude": feature.get("lon")
                }
            # For ways and relations, use center coordinates if available
            elif "center" in feature:
                coords = {
                    "latitude": feature.get("center", {}).get("lat"),
                    "longitude": feature.get("center", {}).get("lon")
                }
            
            # Only include features with valid coordinates
            if coords:
                results.append({
                    "id": feature.get("id"),
                    "type": feature.get("type"),
                    "name": tags.get("name", "Unnamed"),
                    "coordinates": coords,
                    "category": category,
                    "subcategory": tags.get(category),
                    "tags": tags
                })
        
        return {
            "query": {
                "category": category,
                "subcategories": subcategories,
                "bbox": {
                    "min_latitude": min_latitude,
                    "min_longitude": min_longitude,
                    "max_latitude": max_latitude,
                    "max_longitude": max_longitude
                }
            },
            "results": results,
            "count": len(results)
        }
  • Supporting method in the OSMClient class that constructs and executes an Overpass API query to fetch OSM nodes, ways, and relations matching the specified category (and optional subcategories) within the given bounding box.
    async def search_features_by_category(self, 
                                         bbox: Tuple[float, float, float, float],
                                         category: str,
                                         subcategories: List[str] = None) -> List[Dict]:
        """Search for OSM features by category and subcategories"""
        if not self.session:
            raise RuntimeError("OSM client not connected")
        
        overpass_url = "https://overpass-api.de/api/interpreter"
        
        # Build query for specified category and subcategories
        if subcategories:
            subcategory_filters = " or ".join([f'"{category}"="{sub}"' for sub in subcategories])
            query_filter = f'({subcategory_filters})'
        else:
            query_filter = f'"{category}"'
        
        query = f"""
        [out:json];
        (
          node[{query_filter}]({bbox[1]},{bbox[0]},{bbox[3]},{bbox[2]});
          way[{query_filter}]({bbox[1]},{bbox[0]},{bbox[3]},{bbox[2]});
          relation[{query_filter}]({bbox[1]},{bbox[0]},{bbox[3]},{bbox[2]});
        );
        out body;
        """
        
        async with self.session.post(overpass_url, data={"data": query}) as response:
            if response.status == 200:
                data = await response.json()
                return data.get("elements", [])
            else:
                raise Exception(f"Failed to search features by category: {response.status}")
  • The @mcp.tool() decorator registers the search_category function as an MCP tool.
    async def search_category(

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

A4.5/5.0
Behavior4/5

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

With no annotations, the description takes on the full burden. It discloses the return format ('Structured results including...') and that results contain complete location details and metadata. It does not mention edges like limits or sorting, but for a search tool this level of detail is reasonably transparent.

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 well-structured with a one-sentence summary, a brief contextual paragraph, a clean Args list, and a clear Returns section. It avoids wordiness and each sentence earns its place.

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?

The description covers the purpose, all six parameters, and the return structure. However, it does not clarify how it differs from overlapping siblings like 'find_nearby_places' or 'explore_area', which would be useful context but is not essential for basic invocation.

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?

Schema description coverage is 0%, but the description provides a full Args section explaining each parameter with examples (e.g., 'category: Main OSM category…', 'min_latitude: Southern boundary…'). This fully compensates for the schema's lack of descriptions.

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 opens with a clear verb+resource+scope: 'Search for specific types of places within a defined geographic area.' It then specifies a rectangular geographic region and OSM categories, which distinguishes it from point-based 'nearby' searches and other geospatial tools.

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 context on when this tool is useful ('within a neighborhood or city district') but does not explicitly name alternatives or state when to use a different sibling tool. Since context is clear but exclusions are absent, a 4 is appropriate.

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