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
//! A record's at-uri, `at://<did or handle>/<collection>/<rkey>`: the only
//! kind the tools take or follow. Anything else, a repository's or a
//! collection's uri, or one with a query or fragment, is refused.
use atproto::syntax::{is_did, is_handle, is_nsid, is_record_key};
/// A record's at-uri, split into its parts.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AtUri {
/// The repository: a DID, or a handle (lowercased).
pub authority: String,
pub collection: String,
pub rkey: String,
}
impl AtUri {
/// `s` as a record's at-uri, or why it is not one.
pub fn parse(s: &str) -> Result<AtUri, String> {
let bad =
|| format!("Not a record's at-uri (at://<did or handle>/<collection>/<rkey>): {s}");
let rest = s.strip_prefix("at://").ok_or_else(bad)?;
let mut parts = rest.split('/');
let (Some(authority), Some(collection), Some(rkey), None) =
(parts.next(), parts.next(), parts.next(), parts.next())
else {
return Err(bad());
};
let authority = if is_did(authority) {
authority.to_string()
} else if is_handle(authority) {
authority.to_ascii_lowercase()
} else {
return Err(bad());
};
if !is_nsid(collection) || !is_record_key(rkey) {
return Err(bad());
}
Ok(AtUri {
authority,
collection: collection.to_string(),
rkey: rkey.to_string(),
})
}
/// The uri with `did` as its authority.
pub fn with_did(&self, did: &str) -> String {
format!("at://{did}/{}/{}", self.collection, self.rkey)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses() {
let u = AtUri::parse("at://Alice.Example.com/app.bsky.feed.post/3k2a").unwrap();
assert_eq!(
(u.authority.as_str(), u.collection.as_str(), u.rkey.as_str()),
("alice.example.com", "app.bsky.feed.post", "3k2a")
);
assert_eq!(
u.with_did("did:plc:x"),
"at://did:plc:x/app.bsky.feed.post/3k2a"
);
for bad in [
"https://x.com/a/b",
"at://did:plc:x",
"at://did:plc:x/app.bsky.feed.post",
"at://did:plc:x/app.bsky.feed.post/a/b",
"at://did:plc:x/notnsid/a",
"at://did:plc:x/app.bsky.feed.post/a?b",
"at://not_a_handle/app.bsky.feed.post/a",
] {
assert!(AtUri::parse(bad).is_err(), "{bad}");
}
}
}