Skip to main content
Glama
sarunasdaujotis

Vilnius Transport MCP Server

find_closest_stop

Locate the nearest public transport stop in Vilnius using specific latitude and longitude coordinates for efficient route planning.

Instructions

Find the closest public transport stop to given coordinates

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
coordinatesYesCoordinates as 'latitude, longitude' (e.g., '54.687157, 25.279652')

Implementation Reference

  • The main handler function that executes the find_closest_stop tool: validates input, parses coordinates, loads stops, computes distances using helper functions, finds the minimum distance stop, and formats a response with stop details and Google Maps link.
    async def handle_find_closest_stop(arguments: Any) -> List[TextContent]:
        """Handle the find_closest_stop tool call."""
        if not isinstance(arguments, dict) or "coordinates" not in arguments:
            raise ValueError("Invalid arguments: 'coordinates' is required")
    
        try:
            coord_str = arguments["coordinates"]
            logger.info(f'Processing coordinates: {coord_str}')
    
            # Parse coordinates
            lat, lon = parse_coordinates(coord_str)
    
            # Get stops data
            stops_df = gk.get_stops(feed)
    
            # Calculate distances to all stops
            distances = calculate_distances(lat, lon, stops_df)
    
            # Find the closest stop
            closest_idx = distances.idxmin()
            closest_stop = stops_df.loc[closest_idx]
            distance_km = distances[closest_idx]
    
            # Format response
            response_text = (
                f"Closest stop to coordinates ({lat:.6f}, {lon:.6f}):\n"
                f"- {closest_stop['stop_name']}\n"
                f"  ID: {closest_stop['stop_id']}\n"
                f"  Location: {float(closest_stop['stop_lat']):.6f}, {float(closest_stop['stop_lon']):.6f}\n"
                f"  Distance: {distance_km:.2f} km"
            )
    
            logger.info(f'Found closest stop: {closest_stop["stop_name"]}')
    
            return [TextContent(
                type="text",
                text=response_text
            )]
    
        except ValueError as e:
            logger.error(f"Invalid coordinates: {str(e)}")
            return [TextContent(
                type="text",
                text=f"Error: {str(e)}"
            )]
        except Exception as e:
            logger.error(f"Error finding closest stop: {str(e)}")
            raise RuntimeError(f"Error finding closest stop: {str(e)}")
  • The tool schema definition in list_tools(), specifying the name, description, and input schema requiring a 'coordinates' string in 'lat,lon' format.
    Tool(
        name="find_closest_stop",
        description="Find the closest public transport stop to given coordinates",
        inputSchema={
            "type": "object",
            "properties": {
                "coordinates": {
                    "type": "string",
                    "description": "Coordinates as 'latitude, longitude' (e.g., '54.687157, 25.279652')",
                },
            },
            "required": ["coordinates"],
        },
    ),
  • Tool dispatch/registration in the call_tool handler: routes calls to 'find_closest_stop' to the handle_find_closest_stop function.
    elif name == "find_closest_stop":
        return await handle_find_closest_stop(arguments)
  • Helper function to parse and validate coordinates from input string 'latitude, longitude'.
    def parse_coordinates(coord_str: str) -> Tuple[float, float]:
        """Parse coordinates string into latitude and longitude.
    
        Args:
            coord_str: String containing latitude and longitude separated by comma
    
        Returns:
            Tuple of (latitude, longitude) as floats
    
        Raises:
            ValueError: If coordinates are invalid or out of range
        """
        try:
            lat_str, lon_str = coord_str.split(',')
            lat = float(lat_str.strip())
            lon = float(lon_str.strip())
    
            if not (-90 <= lat <= 90) or not (-180 <= lon <= 180):
                raise ValueError("Coordinates out of valid range")
    
            return lat, lon
        except ValueError as e:
            raise ValueError("Invalid coordinates format. Expected 'latitude, longitude'") from e
  • Helper function implementing Haversine formula to compute distances from given lat/lon to all stops in the GTFS stops DataFrame.
    def calculate_distances(lat: float, lon: float, stops_df: 'pd.DataFrame') -> 'pd.Series':
        """Calculate distances from given point to all stops using Haversine formula.
    
        Args:
            lat: Latitude of the point
            lon: Longitude of the point
            stops_df: DataFrame containing stops data
    
        Returns:
            Series containing distances to all stops in kilometers
        """
        R = 6371  # Earth's radius in kilometers
    
        # Convert degrees to radians
        lat1, lon1 = np.radians(lat), np.radians(lon)
        lat2, lon2 = np.radians(stops_df['stop_lat']), np.radians(stops_df['stop_lon'])
    
        # Haversine formula
        dlat = lat2 - lat1
        dlon = lon2 - lon1
    
        a = np.sin(dlat / 2) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2) ** 2
        c = 2 * np.arcsin(np.sqrt(a))
    
        return R * c
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions 'find' but doesn't clarify if this is a read-only operation, how results are returned (e.g., distance, stop details), potential errors (e.g., invalid coordinates), or performance aspects like rate limits. The description lacks critical behavioral traits needed for safe and effective invocation.

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 a single, clear sentence that directly states the tool's function without unnecessary words or fluff. It is front-loaded with the core action and resource, making it efficient and easy to parse, which is ideal for conciseness in tool descriptions.

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?

Given the lack of annotations and output schema, the description is incomplete for a tool that likely returns complex data (e.g., stop names, distances). It doesn't explain what the output includes, how 'closest' is determined (e.g., walking distance, straight-line), or error handling. For a tool with one parameter but potentially rich behavior, more context is needed to guide an agent effectively.

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 input schema has 100% description coverage, with the 'coordinates' parameter well-documented in the schema (e.g., format 'latitude, longitude'). The description adds no additional parameter semantics beyond what the schema provides, such as coordinate range limits or examples of valid inputs. Given the high schema coverage, a baseline score of 3 is appropriate as the schema handles the heavy lifting.

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 'find' and the resource 'closest public transport stop' with the condition 'to given coordinates', making the purpose specific and actionable. However, it doesn't explicitly differentiate from the sibling tool 'find_stops', which might handle multiple stops or different criteria, leaving some ambiguity in sibling differentiation.

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 like 'find_stops', nor does it mention any prerequisites, exclusions, or contextual factors (e.g., transport modes, time of day). It only states the basic function without usage context, which limits its helpfulness for an agent selecting between tools.

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

Related 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/sarunasdaujotis/vilnius-transport-mcp-server'

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