chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.4.0 Latest 5 packages
0
0
//! The text a record tool answers with: a short summary a person could
//! read, and a host without MCP Apps shows alone. A view's `summary` names
//! its noun, each record's label and a detail count, all read from the
//! records; with none, the text says how many records of the collection
//! there are. A query join that says something (`say`) adds a few words
//! of its answer after. Labels are third parties' text, so each is put on
//! one line and cut short; nothing of a lexicon's ever is.
use crate::identity::Identity;
use crate::view::{Path, QueryJoin, Summary};
use serde_json::{Map, Value};
/// The most labels a list's summary names.
const LABELS: usize = 8;
/// Third parties' text on one line, at most `max` characters.
pub fn one_line(s: &str, max: usize) -> String {
let flat: String = s
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.chars()
.filter(|c| !c.is_control())
.collect();
match flat.char_indices().nth(max) {
Some((cut, _)) => format!("{}…", flat[..cut].trim_end()),
None => flat,
}
}
/// `n` of a noun, as `1 photo` or `3 photos`.
pub fn count(n: u64, noun: &[String; 2]) -> String {
format!("{n} {}", if n == 1 { &noun[0] } else { &noun[1] })
}
/// `; more with cursor <c>`, if there is a next page.
fn more(cursor: Option<&str>) -> String {
cursor
.map(|c| format!("; more with cursor {}", one_line(c, 100)))
.unwrap_or_default()
}
/// A record's label, if its binding gives non-empty text.
pub(crate) fn label(s: &Summary, scope: &Value) -> Option<String> {
let text = match s.label.as_ref()?.get(scope)? {
Value::String(t) => t.clone(),
Value::Number(n) => n.to_string(),
_ => return None,
};
Some(one_line(&text, 60)).filter(|t| !t.is_empty())
}
/// A record's detail, as `16 photos`, if its count resolves: a number, or
/// an array's elements, with the detail's children path theirs too, all
/// the way down.
fn detail(s: &Summary, scope: &Value) -> Option<String> {
let (n, noun, children) = s.detail.as_ref()?;
let n = match n.get(scope)? {
Value::Array(items) => counted(items, children.as_ref(), 0),
v => v.as_u64()?,
};
Some(count(n, noun))
}
/// How deep `counted` follows children.
const COUNT_DEPTH: usize = 32;
/// The elements of `items`, and, with `children`, of each one's children,
/// recursively.
fn counted(items: &[Value], children: Option<&Path>, depth: usize) -> u64 {
items
.iter()
.map(|i| {
let below = match children.and_then(|c| c.get(i)).and_then(Value::as_array) {
Some(kids) if depth < COUNT_DEPTH => counted(kids, children, depth + 1),
_ => 0,
};
1 + below
})
.sum()
}
/// `: Coast (12 photos), October (24 photos), …`: the labels of items, as
/// many as resolve, at most eight; nothing if none does.
fn labels(s: &Summary, items: &[Value]) -> String {
let named: Vec<String> = items
.iter()
.filter_map(|r| {
let l = label(s, r)?;
Some(match detail(s, r) {
Some(d) => format!("{l} ({d})"),
None => l,
})
})
.collect();
match named.len() {
0 => String::new(),
n => format!(
": {}{}",
named[..n.min(LABELS)].join(", "),
if n > LABELS { ", …" } else { "" }
),
}
}
/// A page of records: `6 galleries by alice.example.com: Coast (12
/// photos), October (24 photos), …; more with cursor <c>`. A record whose
/// label does not resolve is counted, not named.
pub fn list(s: &Summary, who: &Identity, recs: &[Value], cursor: Option<&str>) -> String {
format!(
"{} by {}{}{}",
count(recs.len() as u64, &s.noun),
who.name(),
labels(s, recs),
more(cursor)
)
}
/// A query's answer, its items: `10 posts from app.bsky.feed.getFeed on
/// api.bsky.app: …; more with cursor <c>`.
pub fn query(
s: &Summary,
method: &str,
host: &str,
items: &[Value],
cursor: Option<&str>,
) -> String {
format!(
"{} from {method} on {host}{}{}",
count(items.len() as u64, &s.noun),
labels(s, items),
more(cursor)
)
}
/// A query's answer that is one thing, as a thread, in its scope
/// (`{ method, service, params, response }`): `Thread: "hello" by
/// alice.example: 3 replies.`; with no label, `Thread from <method> on
/// <host>`.
pub fn query_one(s: &Summary, method: &str, host: &str, scope: &Value) -> String {
let mut noun = s.noun[0].chars();
let head: String = noun
.next()
.map(|c| c.to_uppercase().chain(noun).collect())
.unwrap_or_default();
let named = match label(s, scope) {
Some(l) => format!("{head}: \"{l}\""),
None => format!("{head} from {method} on {host}"),
};
let by =
s.by.as_ref()
.and_then(|b| b.get(scope))
.and_then(Value::as_str)
.map(|b| one_line(b, 64))
.filter(|b| !b.is_empty())
.map(|b| format!(" by {b}"))
.unwrap_or_default();
match detail(s, scope) {
Some(d) => format!("{named}{by}: {d}."),
None => format!("{named}{by}."),
}
}
/// A query's answer with no view's summary: `app.bsky.feed.getFeed on
/// api.bsky.app: 10 items` where it has one array at its top, else
/// `app.bsky.feed.getFeed answered`.
pub fn generic_query(method: &str, host: &str, response: &Value) -> String {
let arrays: Vec<&Vec<Value>> = response
.as_object()
.into_iter()
.flat_map(|o| o.values())
.filter_map(Value::as_array)
.collect();
match arrays.as_slice() {
[one] => format!(
"{method} on {host}: {}",
count(one.len() as u64, &["item".into(), "items".into()])
),
_ => format!("{method} answered"),
}
}
/// One record, in its scope: `"Coast" by alice.example.com: 12 photos.`,
/// or `gallery by alice.example.com.` with no label or detail.
pub fn record(s: &Summary, who: &Identity, scope: &Value) -> String {
let named = match label(s, scope) {
Some(l) => format!("\"{l}\""),
None => s.noun[0].clone(),
};
match detail(s, scope) {
Some(d) => format!("{named} by {}: {d}.", who.name()),
None => format!("{named} by {}.", who.name()),
}
}
/// A page with no view's summary: `25 app.bsky.feed.post records by
/// alice.example.com; more with cursor <c>`.
pub fn generic_list(collection: &str, who: &Identity, n: usize, cursor: Option<&str>) -> String {
let noun = [
format!("{collection} record"),
format!("{collection} records"),
];
format!(
"{} by {}{}",
count(n as u64, &noun),
who.name(),
more(cursor)
)
}
/// One record with no view's summary.
pub fn generic_record(collection: &str, rkey: &str, who: &Identity) -> String {
format!("{collection} record {rkey} by {}", who.name())
}
/// What a query join that says something says of its answer: how many
/// (`5 recent posts`), or its label's first line (`README: knotless keeps
/// a git…`), the first that is no Markdown heading where there is one;
/// none where its answer is null, or its count or label does not resolve.
fn said(j: &QueryJoin, answer: &Value) -> Option<String> {
let say = j.say.as_ref()?;
if let Some(c) = &say.count {
let n = match c.get(answer)? {
Value::Array(items) => items.len() as u64,
v => v.as_u64()?,
};
return Some(count(n, &say.noun));
}
let text = say.label.as_ref()?.get(answer)?.as_str()?;
let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty());
let line = match lines.clone().find(|l| !l.starts_with('#')) {
Some(l) => l,
None => lines.next()?.trim_start_matches('#').trim(),
};
Some(format!("{}: {}", say.noun[0], one_line(line, 60)))
}
/// The text, with what its query joins say of their answers after it, in
/// their order: `…: 4 open issues. README: knotless keeps…; latest release:
/// 0.15.0.`
pub fn with_said(text: String, joins: &[QueryJoin], answers: &Map<String, Value>) -> String {
let said: Vec<String> = joins
.iter()
.filter_map(|j| said(j, answers.get(&j.name)?))
.collect();
if said.is_empty() {
return text;
}
let stop = if text.ends_with('.') { "" } else { "." };
format!("{text}{stop} {}.", said.join("; "))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::view;
use serde_json::json;
fn who() -> Identity {
Identity {
did: "did:plc:x".into(),
handle: Some("alice.example.com".into()),
pds: "https://pds.example".into(),
}
}
fn summary(s: Value) -> Summary {
let doc = json!({ "collection": "a.b.c", "description": "d",
"list": { "summary": s, "layout": { "component": "Badge", "props": { "value": "x" } } } });
view::parse(&doc, false)
.unwrap()
.list
.unwrap()
.summary
.unwrap()
}
fn gallery(title: Option<&str>, n: u64) -> Value {
json!({ "value": { "title": title }, "joins": { "items": { "total": n } } })
}
#[test]
fn lists() {
let s = summary(
json!({ "noun": ["gallery", "galleries"], "label": { "$": "value.title" },
"detail": { "count": { "$": "joins.items.total" }, "noun": ["photo", "photos"] } }),
);
let recs = [
gallery(Some("bodega"), 16),
gallery(None, 3),
gallery(Some("oak\nleaf"), 1),
];
assert_eq!(
list(&s, &who(), &recs, Some("c1")),
"3 galleries by alice.example.com: bodega (16 photos), oak leaf (1 photo); more with cursor c1"
);
let many: Vec<Value> = (0..10)
.map(|i| gallery(Some(&format!("g{i}")), 1))
.collect();
let text = list(&s, &who(), &many, None);
assert!(
text.starts_with("10 galleries by alice.example.com: g0 (1 photo), "),
"{text}"
);
assert!(text.ends_with("g7 (1 photo), …"), "{text}");
assert_eq!(
list(&s, &who(), &[], None),
"0 galleries by alice.example.com"
);
let bare = summary(json!({ "noun": ["like", "likes"] }));
assert_eq!(
list(&bare, &who(), &recs[..1], None),
"1 like by alice.example.com"
);
}
#[test]
fn records() {
let s = summary(
json!({ "noun": ["gallery", "galleries"], "label": { "$": "value.title" },
"detail": { "count": { "$": "joins.items.total" }, "noun": ["photo", "photos"] } }),
);
assert_eq!(
record(&s, &who(), &gallery(Some("bodega"), 16)),
"\"bodega\" by alice.example.com: 16 photos."
);
assert_eq!(
record(&s, &who(), &json!({ "value": {} })),
"gallery by alice.example.com."
);
let literal =
summary(json!({ "noun": ["playlist", "playlists"], "label": "Liked tracks" }));
assert_eq!(
record(&literal, &who(), &json!({})),
"\"Liked tracks\" by alice.example.com."
);
// A number is a label as text; anything else no label.
let numbered = summary(json!({ "noun": ["track", "tracks"], "label": { "$": "value.n" } }));
assert_eq!(
record(&numbered, &who(), &json!({ "value": { "n": 7 } })),
"\"7\" by alice.example.com."
);
assert_eq!(
record(&numbered, &who(), &json!({ "value": { "n": { "x": 1 } } })),
"track by alice.example.com."
);
}
#[test]
fn generic() {
assert_eq!(
generic_list("app.bsky.feed.post", &who(), 25, Some("c")),
"25 app.bsky.feed.post records by alice.example.com; more with cursor c"
);
assert_eq!(
generic_record("app.bsky.feed.post", "3k", &who()),
"app.bsky.feed.post record 3k by alice.example.com"
);
assert_eq!(one_line("abcdef", 3), "abc…");
}
#[test]
fn queries() {
let s = summary(json!({ "noun": ["post", "posts"], "label": { "$": "post.record.text" } }));
let items = [
json!({ "post": { "record": { "text": "hello" } } }),
json!({ "post": { "record": {} } }),
];
assert_eq!(
query(
&s,
"app.bsky.feed.getFeed",
"api.bsky.app",
&items,
Some("c")
),
"2 posts from app.bsky.feed.getFeed on api.bsky.app: hello; more with cursor c"
);
assert_eq!(
generic_query(
"app.bsky.feed.getFeed",
"api.bsky.app",
&json!({ "feed": [1, 2], "cursor": "c" })
),
"app.bsky.feed.getFeed on api.bsky.app: 2 items"
);
assert_eq!(
generic_query("x.y.z", "h", &json!({ "a": [], "b": [] })),
"x.y.z answered"
);
}
#[test]
fn query_joins_say_a_little() {
let doc = json!({ "method": "a.b.getRepo", "service": "did:web:x.example#svc", "description": "d",
"query": { "join": [
{ "as": "readme", "query": "a.b.getFile", "say": { "noun": ["README", "READMEs"], "label": "text" } },
{ "as": "posts", "query": "a.b.getFeed", "say": { "noun": ["recent post", "recent posts"], "count": "feed" } },
{ "as": "quiet", "query": "a.b.getFeed" },
{ "as": "gone", "query": "a.b.getFeed", "say": { "noun": ["x", "xs"], "count": "feed" } }
], "layout": { "component": "Badge", "props": { "value": "x" } } } });
let joins = view::parse(&doc, false).unwrap().query.unwrap().queries;
let answers = json!({
"readme": { "text": "\n# knotless\n\nknotless keeps a git repository in an atproto account, the kind of account Bluesky runs on." },
"posts": { "feed": [1, 2, 3, 4, 5] },
"quiet": { "feed": [1] },
"gone": null
});
let answers = answers.as_object().unwrap();
assert_eq!(
with_said(
"Repository: \"knotless\": 4 open issues.".into(),
&joins,
answers
),
"Repository: \"knotless\": 4 open issues. README: knotless keeps a git repository in an atproto account, the k…; 5 recent posts."
);
assert_eq!(
with_said(
"6 posts by alice; more with cursor c".into(),
&joins[1..],
answers
),
"6 posts by alice; more with cursor c. 5 recent posts."
);
// Nothing to say: the text as it was.
assert_eq!(with_said("x.".into(), &joins[2..], answers), "x.");
let long = json!({ "readme": { "text": "A".repeat(100) } });
assert_eq!(
with_said("x.".into(), &joins[..1], long.as_object().unwrap()),
format!("x. README: {}….", "A".repeat(60))
);
// A heading alone is said without its marks.
let heading = json!({ "readme": { "text": "## Title\n" } });
assert_eq!(
with_said("x.".into(), &joins[..1], heading.as_object().unwrap()),
"x. README: Title."
);
// A count that is a number, as it is.
let counted = json!({ "posts": { "feed": 12 } });
assert_eq!(
with_said("x.".into(), &joins[1..2], counted.as_object().unwrap()),
"x. 12 recent posts."
);
}
}