~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
239 lines · 9.7 KB Raw History
//! A tile's call made canonical, so the same call written otherwise is
//! found on a canvas: its keys sorted, its empty values dropped, a query
//! naming no service the one its bundled view calls, an app's page's
//! domain lowercased, and the accounts it names by handle named by DID (a
//! `query`'s at-uri and at-identifier params as its lexicon declares them;
//! `get_record`'s uri, `list_records`', `describe_repo`'s and
//! `describe_app`'s actor). A handle that does not resolve is kept as
//! given, lowercased: an add is never refused for it.

use super::{Refused, Tile, Who};
use crate::Hud;
use crate::{view, xrpc};
use serde_json::{Map, Value, json};

/// Nothing given: null, "", [] or {}.
fn empty(v: &Value) -> bool {
    v.is_null()
        || v.as_str() == Some("")
        || v.as_array().is_some_and(Vec::is_empty)
        || v.as_object().is_some_and(Map::is_empty)
}

/// An object's keys sorted, its empty values dropped.
fn tidy(map: Map<String, Value>) -> Map<String, Value> {
    let mut pairs: Vec<(String, Value)> = map.into_iter().filter(|(_, v)| !empty(v)).collect();
    pairs.sort_by(|a, b| a.0.cmp(&b.0));
    pairs.into_iter().collect()
}

impl Hud {
    /// `arguments` of the read tool `tool` as the same call is always
    /// written; what is not an object, as given.
    pub async fn canonical_call(&self, tool: &str, arguments: &Value) -> Value {
        let Some(given) = arguments.as_object() else {
            return arguments.clone();
        };
        let mut args = tidy(given.clone());
        let resolve =
            |h: String| async move { Ok::<_, String>(self.handle_did(&h).await.unwrap_or(h)) };
        match tool {
            "query" => {
                let Some(method) = args.get("method").and_then(Value::as_str) else {
                    return Value::Object(args);
                };
                let method = method.trim().to_string();
                args.insert("method".into(), json!(method));
                // No service named: the one its bundled view calls, named.
                if !args.contains_key("view")
                    && !args.contains_key("service")
                    && let Some(service) = view::for_method(&method).and_then(|v| v.service.clone())
                {
                    args.insert("service".into(), json!(service));
                }
                if let Some(Value::Object(p)) = args.get("params") {
                    let mut params = tidy(p.clone());
                    if let Some(doc) = self.lexicon_doc(&method).await
                        && let Ok(def) = xrpc::query_def(&method, &doc)
                    {
                        let _ = xrpc::handles_to_dids(def, &mut params, resolve).await;
                        let _ = xrpc::identifiers_to_dids(def, &mut params, resolve).await;
                    }
                    args.insert("params".into(), Value::Object(params));
                }
            }
            "get_record" => {
                let def = json!({ "parameters": { "properties": {
                    "uri": { "type": "string", "format": "at-uri" } } } });
                if let Some(Value::String(u)) = args.get("uri") {
                    let trimmed = u.trim().to_string();
                    args.insert("uri".into(), json!(trimmed));
                }
                let _ = xrpc::handles_to_dids(&def, &mut args, resolve).await;
            }
            "list_records" | "describe_repo" | "describe_app" => {
                if let Some(Value::String(d)) = args.get("domain") {
                    let domain = d.trim().trim_end_matches('.').to_ascii_lowercase();
                    args.insert("domain".into(), json!(domain));
                }
                let def = json!({ "parameters": { "properties": {
                    "actor": { "type": "string", "format": "at-identifier" } } } });
                let _ = xrpc::identifiers_to_dids(&def, &mut args, resolve).await;
            }
            _ => {}
        }
        Value::Object(tidy(args))
    }

    /// The tile on a canvas a member may change whose call is `tool` with
    /// `canonical` (`canonical_call`'s), the tiles' own made canonical too:
    /// they may have been added before calls were. A record a bundled view
    /// draws as its query (`view::routed_call`) is the same tile opened
    /// either way, by `get_record` or by that query.
    pub async fn same_tile(
        &self,
        who: Who<'_>,
        canvas: &str,
        tool: &str,
        canonical: &Value,
    ) -> Result<Option<Tile>, Refused> {
        let wanted = self.as_query(tool, canonical).await;
        for tile in self.canvases.tiles_to_edit(who, canvas).await? {
            if tile.tool == tool && tile.arguments == *canonical {
                return Ok(Some(tile));
            }
            let given = self.canonical_call(&tile.tool, &tile.arguments).await;
            if self.as_query(&tile.tool, &given).await == wanted {
                return Ok(Some(tile));
            }
        }
        Ok(None)
    }

    /// A canonical call as the query it draws: a `get_record` of a record a
    /// bundled view draws as its query, with no inline view, that query's;
    /// any other as it is.
    async fn as_query(&self, tool: &str, canonical: &Value) -> (String, Value) {
        if tool == "get_record"
            && canonical.get("view").is_none()
            && let Some(args) = canonical["uri"].as_str().and_then(view::routed_call)
        {
            return ("query".into(), self.canonical_call("query", &args).await);
        }
        (tool.to_string(), canonical.clone())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tidy_sorts_and_drops_empties() {
        let m = json!({ "b": 1, "a": "", "c": null, "d": [], "e": {}, "f": "x" });
        let t = tidy(m.as_object().unwrap().clone());
        assert_eq!(t.keys().collect::<Vec<_>>(), ["b", "f"]);
    }

    #[tokio::test]
    async fn calls_written_otherwise_made_the_same() {
        let dir = std::env::temp_dir().join(format!("hud-canonical-{}", atproto::jose::random(6)));
        let h = Hud::new(crate::Config {
            port: 0,
            bind: "::".parse().unwrap(),
            public_origin: "https://hud.test".into(),
            cache_dir: dir.join("cache"),
            blob_cache_bytes: 0,
            cache_memory_bytes: 1 << 24,
            data_dir: dir,
            oauth: false,
            oauth_scope: crate::scope::asked(crate::view::views(), true, false),
            oauth_include: None,
            workspace: true,
            sign_up_pds: crate::config::SIGN_UP_PDS.into(),
            client: Default::default(),
            operators: Vec::new(),
            logs: false,
            logs_keep: crate::logs::KEEP,
            spaces: false,
            plc_url: "http://127.0.0.1:9".into(),
            handle_resolver: None,
            allow_private: false,
            backlinks: crate::backlinks::Backlinks::None,
            favicons: None,
            image_cdn: None,
            relay: None,
        })
        .unwrap();
        // What is not an object, as given.
        assert_eq!(h.canonical_call("query", &json!("x")).await, json!("x"));
        // An app's page's domain lowercased, its trailing dot dropped.
        assert_eq!(
            h.canonical_call(
                "describe_app",
                &json!({ "domain": " BSKY.App. ", "view": null })
            )
            .await,
            json!({ "domain": "bsky.app" })
        );
        // A record named by no URI is left as given.
        assert_eq!(
            h.canonical_call("get_record", &json!({ "cid": "bafy", "view": {} }))
                .await,
            json!({ "cid": "bafy" })
        );
        // A query: its method trimmed, its bundled view's service named,
        // its params tidied.
        let feed = "at://did:plc:x/app.bsky.feed.generator/d";
        let expected = json!({ "method": "app.bsky.feed.getFeed",
                               "params": { "feed": feed, "limit": 5 },
                               "service": "did:web:api.bsky.app#bsky_appview" });
        assert_eq!(
            h.canonical_call(
                "query",
                &json!({ "method": " app.bsky.feed.getFeed ",
                         "params": { "limit": 5, "cursor": "", "feed": feed } })
            )
            .await,
            expected
        );
        // A service named stays; params of a method with no lexicon, tidied
        // alone.
        let named = json!({ "method": "app.bsky.feed.getFeed", "service": "did:web:x#y" });
        assert_eq!(h.canonical_call("query", &named).await, named);
        assert_eq!(
            h.canonical_call(
                "query",
                &json!({ "method": "nope", "params": { "a": 1, "b": "" } })
            )
            .await,
            json!({ "method": "nope", "params": { "a": 1 } })
        );
        // One with no method, as given, tidied.
        assert_eq!(
            h.canonical_call("query", &json!({ "params": { "a": 1 }, "view": null }))
                .await,
            json!({ "params": { "a": 1 } })
        );
        // A record's URI trimmed; an actor by DID as it is; any other tool
        // tidied alone.
        assert_eq!(
            h.canonical_call("get_record", &json!({ "uri": " at://did:plc:a/a.b.c/1 " }))
                .await,
            json!({ "uri": "at://did:plc:a/a.b.c/1" })
        );
        assert_eq!(
            h.canonical_call(
                "list_records",
                &json!({ "collection": "a.b.c", "actor": "did:plc:a" })
            )
            .await,
            json!({ "actor": "did:plc:a", "collection": "a.b.c" })
        );
        assert_eq!(
            h.canonical_call("describe_method", &json!({ "method": "a.b.c", "x": "" }))
                .await,
            json!({ "method": "a.b.c" })
        );
    }
}