Skip to content
Minden projekt
python geospatial scikit-learn mcp cli

Nearest Cities

Spatial neighbour search on 30,000+ US cities — built as a take-home assignment in four hours, then refined into a library with a CLI, an interactive REPL, and an MCP server.

A startup asked me to write a tool that, given a dataset of US cities, finds every city within a configurable radius of each city. The constraint was implicit: it had to be fast enough to be useful on the full 30,000-row dataset.

The first version took four hours. The refined version is below.

The Core: BallTree with Haversine

The naive approach — compute geopy.distance for every pair — is O(n²) and takes minutes on 30,000 cities. Instead, the cities are indexed once in a BallTree using the haversine metric, which operates directly on radians and respects the curvature of the earth. Each lookup is then O(log n).

The bulk path (query_all) issues a single tree.query_radius call per chunk over the entire input array rather than looping per row. This keeps the hot path inside scikit-learn’s C extension and lets a progress callback fire at chunk boundaries without serialising to per-row Python.

finder = NearestCityFinder(cities_df)
finder.query(row_index, distance_km=50)          # single city
finder.query_by_coords(lat, lng, distance_km=50) # arbitrary point
finder.query_all(distance_km=50)                 # vectorised: all rows

Three Interfaces from One Core

The library is the foundation; the interfaces are additive:

CLI batch mode (annotate) reads a CSV, annotates every row with its neighbours, and writes a new CSV. A rich progress bar tracks the chunked work.

Interactive REPL (query) drops into a shell with TAB autocompletion on city names, disambiguation prompts when names clash across states (Springfield, MA vs Springfield, IL), and a /distance command to adjust the radius mid-session.

MCP stdio server (mcp) exposes the same functionality as two tools — find_nearest_cities and annotate_csv — over the Model Context Protocol, making the library composable with any MCP-capable AI agent. This was not in the original spec; it took about an hour and makes the tool considerably more useful.

What the Submission Actually Tested

Take-home assignments at this level are rarely about whether you can loop over a list. They test whether you reach for the right data structure (BallTree, not a distance matrix), whether you separate concerns (library vs CLI vs server), and whether you ship something that a team could extend without rewriting. The MCP server in particular is a natural extension of clean API design — when your library is a proper object with a stable interface, wrapping it in a new transport is straightforward.

Tests cover the library, REPL, MCP server, and CLI with a small synthetic fixture. An opt-in integration test runs against the full dataset if downloaded; otherwise it skips automatically.