chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.5.0 Latest 5 packages
0
0
//! Places a person names, for a gallery's location (`find_place`, hidden
//! from the model): OpenStreetMap's Nominatim searched for their words, as
//! Grain does, each result a place as Grain writes one: its name, the H3
//! cell (resolution 10) its point is in, and its address; or the place at
//! a point, a photo's GPS, by Nominatim's reverse, as Grain suggests a
//! photo's place. Nominatim asks for a User-Agent naming the app, and few
//! requests: each answer is kept a day, and the view searches only once
//! typing pauses.
use crate::Hud;
use crate::oauth::Account;
use crate::tools::{Args, Output, Refusal};
use h3o::{LatLng, Resolution};
use serde_json::{Map, Value, json};
use std::sync::Arc;
use std::time::Duration;
use url::Url;
/// Nominatim's search.
static NOMINATIM: std::sync::LazyLock<Url> = std::sync::LazyLock::new(|| {
Url::parse("https://nominatim.openstreetmap.org/search").expect("Nominatim's URL")
});
/// How many places a search answers.
const LIMIT: &str = "6";
/// How long a search has.
const WAIT: Duration = Duration::from_secs(8);
/// The most of its answer read.
const MAX: usize = 512 * 1024;
/// How long a search's answer is kept.
const KEEP: Duration = Duration::from_secs(24 * 60 * 60);
/// The most characters searched for.
const Q_MAX: usize = 200;
/// The tool's definition: hidden from the model, a gallery form's.
pub fn definition() -> Value {
json!({
"name": "find_place",
"title": "Find a place",
"description": "Search OpenStreetMap for places by name or address, or find the place at a point (a photo's GPS), for a gallery's location: each its name, its H3 cell (resolution 10) and its address. Called by the view.",
"inputSchema": {
"type": "object",
"properties": {
"q": { "type": "string", "minLength": 1, "maxLength": Q_MAX,
"description": "What to search for: a place's name or address." },
"lat": { "type": "number", "minimum": -90, "maximum": 90,
"description": "With lon, in place of q: the point's latitude, in degrees." },
"lon": { "type": "number", "minimum": -180, "maximum": 180,
"description": "With lat: the point's longitude, in degrees." },
},
"additionalProperties": false,
},
"annotations": { "title": "Find a place", "readOnlyHint": true,
"destructiveHint": false, "idempotentHint": true, "openWorldHint": true },
"_meta": { "ui": { "visibility": ["app"] } },
})
}
/// A string field of `v`, if it says something.
fn text<'a>(v: &'a Value, k: &str) -> Option<&'a str> {
v[k].as_str().map(str::trim).filter(|s| !s.is_empty())
}
/// The H3 cell at resolution 10 of a point, as h3-js's `latLngToCell`
/// writes it: lowercase hex.
pub fn cell(lat: f64, lon: f64) -> Option<String> {
let at = LatLng::new(lat, lon).ok()?;
Some(at.to_cell(Resolution::Ten).to_string())
}
/// A Nominatim result as a place: `{ name, value, address }`, as Grain
/// makes one (its `formatLocationName` and `extractAddress`); none
/// without a point or a country.
fn place(r: &Value) -> Option<Value> {
let lat: f64 = text(r, "lat")?.parse().ok()?;
let lon: f64 = text(r, "lon")?.parse().ok()?;
let a = &r["address"];
let country = text(a, "country_code")
.filter(|c| c.len() == 2 && c.bytes().all(|b| b.is_ascii_alphabetic()))?
.to_ascii_uppercase();
let locality = text(a, "city")
.or_else(|| text(a, "town"))
.or_else(|| text(a, "village"));
let region = text(a, "state");
let street = text(a, "road").map(|road| match text(a, "house_number") {
Some(n) => format!("{n} {road}"),
None => road.to_string(),
});
let name = match text(r, "name") {
Some(n) => n.to_string(),
None => {
let context: Vec<&str> = [locality, region, text(a, "country")]
.into_iter()
.flatten()
.collect();
match context.is_empty() {
false => context.join(", "),
true => text(r, "display_name")?
.split(',')
.next()
.unwrap_or_default()
.trim()
.to_string(),
}
}
};
let mut address = Map::new();
address.insert("country".into(), json!(country));
for (k, v) in [
("region", region),
("locality", locality),
("street", street.as_deref()),
("postalCode", text(a, "postcode")),
] {
if let Some(v) = v {
address.insert(k.into(), json!(v));
}
}
Some(json!({ "name": name, "value": cell(lat, lon)?, "address": address }))
}
/// A Nominatim answer's places, those it can make one of.
fn places(answer: &Value) -> Vec<Value> {
answer
.as_array()
.into_iter()
.flatten()
.filter_map(place)
.collect()
}
impl Hud {
pub(crate) async fn find_place_tool(
&self,
arguments: Option<&Value>,
account: Option<&Account>,
) -> Result<Output, Refusal> {
// A composer's alone, as the account: no one else searches
// Nominatim through HUD, which its usage policy holds to it.
if account.is_none() {
return Err(Refusal::SignIn);
}
self.find_place(arguments, &NOMINATIM).await
}
/// `find_place`, its places searched for at `search` (Nominatim's), or
/// with `lat` and `lon`, found at that point by its reverse.
async fn find_place(&self, arguments: Option<&Value>, search: &Url) -> Result<Output, Refusal> {
let args = Args::of(arguments, &["q", "lat", "lon"])?;
if args.0.contains_key("lat") || args.0.contains_key("lon") {
return self.place_at(&args, search).await;
}
let q = args.required("q")?.trim();
if q.chars().count() > Q_MAX {
return Err(format!("q is at most {Q_MAX} characters").into());
}
let key = q
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.to_lowercase();
let found = match self.places.get(&key) {
Some(found) => found,
None => {
let mut url = search.clone();
url.query_pairs_mut()
.append_pair("format", "jsonv2")
.append_pair("addressdetails", "1")
.append_pair("limit", LIMIT)
.append_pair("q", &key);
let found = Arc::new(Value::Array(places(&self.nominatim(url).await?)));
self.places.put(key, found.clone(), KEEP);
found
}
};
let n = found.as_array().map_or(0, Vec::len);
Ok(Output {
text: format!("{n} places for \"{q}\"."),
structured: json!({ "places": *found }),
meta: json!({}),
})
}
/// `find_place` at a point, as a photo's GPS gives it: the place
/// Nominatim's reverse (beside `search`) finds there, if any, its cell
/// the point's own, as Grain makes a photo's; asked for and kept to 5
/// decimals (a metre or so).
async fn place_at(&self, args: &Args<'_>, search: &Url) -> Result<Output, Refusal> {
let degrees = |k: &str, max: f64| {
args.0
.get(k)
.and_then(Value::as_f64)
.filter(|d| d.abs() <= max)
.map(|d| (d * 1e5).round() / 1e5)
};
let (Some(lat), Some(lon)) = (degrees("lat", 90.0), degrees("lon", 180.0)) else {
return Err("lat and lon are degrees, given together".to_string().into());
};
let key = format!("@{lat},{lon}");
let found = match self.places.get(&key) {
Some(found) => found,
None => {
let mut url = search.join("reverse").expect("Nominatim's reverse");
url.query_pairs_mut()
.append_pair("format", "jsonv2")
.append_pair("addressdetails", "1")
.append_pair("lat", &lat.to_string())
.append_pair("lon", &lon.to_string());
let there = place(&self.nominatim(url).await?).and_then(|mut p| {
p["value"] = cell(lat, lon)?.into();
Some(p)
});
let found = Arc::new(Value::Array(there.into_iter().collect()));
self.places.put(key, found.clone(), KEEP);
found
}
};
let n = found.as_array().map_or(0, Vec::len);
Ok(Output {
text: format!("{n} {} there.", if n == 1 { "place" } else { "places" }),
structured: json!({ "places": *found }),
meta: json!({}),
})
}
/// What Nominatim answers at `url`, its search or its reverse.
async fn nominatim(&self, url: Url) -> Result<Value, String> {
let agent = format!(
"HUD/{} (+{})",
env!("CARGO_PKG_VERSION"),
self.config.public_origin
);
let req = self
.net
.get(&url)?
.header(reqwest::header::USER_AGENT, agent)
.header(reqwest::header::ACCEPT, "application/json");
let got = self
.net
.send(req, WAIT, MAX)
.await
.map_err(|f| format!("Could not search OpenStreetMap: {f}"))?;
if got.status != 200 {
return Err(format!("OpenStreetMap's search refused ({})", got.status));
}
serde_json::from_slice(&got.body)
.map_err(|_| "OpenStreetMap's search answered something unreadable".to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::writes::tests::{closed_port, json_answer, refused as err, served};
#[tokio::test]
async fn places_searched_and_kept() {
let s = served(|a| match a.path.as_str() {
"/search" if a.query.contains("q=katz") => (
200,
"application/json",
include_bytes!("testdata/nominatim.json").to_vec(),
),
"/search" if a.query.contains("q=busy") => json_answer(429, json!({})),
_ => (200, "application/json", b"<html>".to_vec()),
})
.await;
let search = Url::parse(&format!("{}/search", s.url)).unwrap();
let find = async |q: &str| s.hud.find_place(Some(&json!({ "q": q })), &search).await;
let out = find(" Katz's DELI ").await.unwrap();
assert_eq!(out.text, "3 places for \"Katz's DELI\".");
assert_eq!(out.structured["places"][0]["name"], "Katz's Delicatessen");
// Asked as Nominatim asks to be, its words as one key; then kept.
{
let asked = s.asked.lock().unwrap();
assert_eq!(asked.len(), 1);
let q: Vec<(String, String)> = url::form_urlencoded::parse(asked[0].query.as_bytes())
.into_owned()
.collect();
let pairs = |k: &str, v: &str| (k.to_string(), v.to_string());
assert_eq!(
q,
[
pairs("format", "jsonv2"),
pairs("addressdetails", "1"),
pairs("limit", "6"),
pairs("q", "katz's deli")
]
);
assert_eq!(
asked[0].headers["user-agent"],
format!("HUD/{} (+https://hud.test)", env!("CARGO_PKG_VERSION"))
);
}
let again = find("katz's deli").await.unwrap();
assert_eq!(again.structured, out.structured);
assert_eq!(s.asked.lock().unwrap().len(), 1);
// Its refusals, and answers it cannot read, are errors, not kept.
assert_eq!(
err(find("busy").await),
"OpenStreetMap's search refused (429)"
);
assert_eq!(
err(find("lisbon").await),
"OpenStreetMap's search answered something unreadable"
);
assert_eq!(err(find("lisbon").await), err(find("lisbon").await));
assert_eq!(s.asked.lock().unwrap().len(), 5);
let nowhere =
Url::parse(&format!("http://127.0.0.1:{}/search", closed_port().await)).unwrap();
let e = err(s.hud.find_place(Some(&json!({ "q": "x" })), &nowhere).await);
assert!(e.starts_with("Could not search OpenStreetMap: "), "{e}");
assert_eq!(err(find(" ").await), "q is required");
// Signed in, words past 200 characters are refused before a search.
let q = "a".repeat(201);
assert_eq!(
err(s
.hud
.find_place_tool(Some(&json!({ "q": q })), Some(&s.account))
.await),
"q is at most 200 characters"
);
assert_eq!(s.asked.lock().unwrap().len(), 5);
}
/// At a photo's point, the place Nominatim's reverse finds there, its
/// cell the point's own; nowhere it finds none; asked to 5 decimals,
/// and kept; a point without both degrees, or past them, refused.
#[tokio::test]
async fn the_place_at_a_point() {
let s = served(|a| match a.path.as_str() {
"/reverse" if a.query.contains("lat=40.72") => {
let all: Value =
serde_json::from_str(include_str!("testdata/nominatim.json")).unwrap();
json_answer(200, all[0].clone())
}
_ => json_answer(200, json!({ "error": "Unable to geocode" })),
})
.await;
let search = Url::parse(&format!("{}/search", s.url)).unwrap();
let at = async |args: Value| s.hud.find_place(Some(&args), &search).await;
let katz = at(json!({ "lat": 40.722_312_345, "lon": -73.987_4 }))
.await
.unwrap();
assert_eq!(katz.text, "1 place there.");
let place = &katz.structured["places"][0];
assert_eq!(place["name"], "Katz's Delicatessen");
assert_eq!(place["value"], cell(40.72231, -73.9874).unwrap());
assert_eq!(place["address"]["street"], "205 East Houston Street");
{
let asked = s.asked.lock().unwrap();
assert_eq!(asked[0].path, "/reverse");
let q: Vec<(String, String)> = url::form_urlencoded::parse(asked[0].query.as_bytes())
.into_owned()
.collect();
let pairs = |k: &str, v: &str| (k.to_string(), v.to_string());
assert_eq!(
q,
[
pairs("format", "jsonv2"),
pairs("addressdetails", "1"),
pairs("lat", "40.72231"),
pairs("lon", "-73.9874")
]
);
}
// The same point, near enough: kept.
let again = at(json!({ "lat": 40.722_311, "lon": -73.987_4 }))
.await
.unwrap();
assert_eq!(again.structured, katz.structured);
assert_eq!(s.asked.lock().unwrap().len(), 1);
// Where it finds nothing, no places.
let sea = at(json!({ "lat": 0, "lon": 0 })).await.unwrap();
assert_eq!(
(sea.text, sea.structured),
("0 places there.".to_string(), json!({ "places": [] }))
);
for args in [
json!({ "lat": 1 }),
json!({ "lon": 1 }),
json!({ "lat": 91, "lon": 0 }),
json!({ "lat": "1", "lon": 0 }),
] {
assert_eq!(
err(at(args).await),
"lat and lon are degrees, given together"
);
}
assert_eq!(s.asked.lock().unwrap().len(), 2);
}
#[test]
fn cells_as_h3_js_makes_them() {
// h3-js: latLngToCell(40.7128, -74.0060, 10).
assert_eq!(cell(40.7128, -74.0060).as_deref(), Some("8a2a10728907fff"));
assert_eq!(cell(f64::NAN, 0.0), None);
}
#[test]
fn nominatim_answers_as_places() {
let answer: Value = serde_json::from_str(include_str!("testdata/nominatim.json")).unwrap();
let got = places(&answer);
assert_eq!(
got,
vec![
json!({ "name": "Katz's Delicatessen", "value": "8a2a1072cb77fff",
"address": { "country": "US", "region": "New York", "locality": "New York",
"street": "205 East Houston Street", "postalCode": "10002" } }),
json!({ "name": "Brooklyn", "value": "8a2a10766407fff",
"address": { "country": "US", "region": "New York", "locality": "New York" } }),
json!({ "name": "Brooklyn", "value": "8a2640c843b7fff",
"address": { "country": "US", "region": "Illinois", "locality": "Brooklyn" } }),
]
);
}
#[test]
fn named_as_grain_names_them() {
// No name: the city, state and country; else the display name's first part.
let r = json!({ "lat": "48.8566", "lon": "2.3522", "name": "",
"display_name": "Somewhere, Paris, France",
"address": { "town": "Paris", "state": "Île-de-France", "country": "France",
"country_code": "fr", "road": "Rue de Rivoli" } });
let p = place(&r).unwrap();
assert_eq!(p["name"], "Paris, Île-de-France, France");
assert_eq!(p["address"]["street"], "Rue de Rivoli");
assert_eq!(p["address"]["country"], "FR");
let r = json!({ "lat": "0", "lon": "0", "display_name": "Null Island, Atlantic",
"address": { "country_code": "zz" } });
assert_eq!(place(&r).unwrap()["name"], "Null Island");
// No country: no place.
assert_eq!(
place(&json!({ "lat": "0", "lon": "0", "name": "Sea" })),
None
);
}
}