~ 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
500 lines · 20.3 KB Raw History
//! Feed interactions, as Bluesky's app sends them: what a signed-in person
//! saw of a feed, opened, or asked more or less of, told to the feed's own
//! generator so it can shape what it serves them
//! (`app.bsky.feed.sendInteractions`). The view alone calls it
//! (`send_interactions`, hidden from the model), for a trusted feed view
//! that reports interactions.
//!
//! The feed's generator is read from the AppView
//! (`app.bsky.feed.getFeedGenerator`, through the account's PDS) and kept an
//! hour: the service DID that takes interactions, and whether it does. The
//! interactions then go through the account's PDS, proxied to that service
//! (`atproto-proxy: <did>#bsky_fg`), so the PDS signs for the account. A
//! feed that takes none is answered quietly, so the view stops sending.

use crate::Hud;
use crate::oauth::Account;
use crate::pds::error_name;
use crate::tools::{Args, Output, Refusal};
use crate::uri::AtUri;
use crate::xrpc::{Caller, Service};
use serde_json::{Value, json};
use std::time::Duration;

/// A feed generator's record collection.
const GENERATOR: &str = "app.bsky.feed.generator";
/// The query a generator's view is read with, and the procedure that
/// sends interactions.
const GET_GENERATOR: &str = "app.bsky.feed.getFeedGenerator";
pub(crate) const SEND: &str = "app.bsky.feed.sendInteractions";
/// The AppView generators' views are read from.
pub(crate) const APPVIEW: &str = "did:web:api.bsky.app#bsky_appview";
/// The fragment of a generator's service that takes interactions.
const FEED_GENERATOR: &str = "bsky_fg";
/// How long a generator's view is kept.
const KEEP: Duration = Duration::from_secs(3600);
/// The most interactions one call sends.
const MAX: usize = 100;
/// The longest `feedContext` and `reqId`, as the lexicon has them.
const FEED_CONTEXT_MAX: usize = 2000;
const REQ_ID_MAX: usize = 100;
/// What the quiet answer of a feed that takes none says.
const NOT_TAKEN: &str = "the feed doesn't take interactions";

/// The events an interaction may be (`app.bsky.feed.defs`).
pub const EVENTS: &[&str] = &[
    "app.bsky.feed.defs#requestLess",
    "app.bsky.feed.defs#requestMore",
    "app.bsky.feed.defs#clickthroughItem",
    "app.bsky.feed.defs#clickthroughAuthor",
    "app.bsky.feed.defs#clickthroughReposter",
    "app.bsky.feed.defs#clickthroughEmbed",
    "app.bsky.feed.defs#interactionSeen",
    "app.bsky.feed.defs#interactionLike",
    "app.bsky.feed.defs#interactionRepost",
    "app.bsky.feed.defs#interactionReply",
    "app.bsky.feed.defs#interactionQuote",
    "app.bsky.feed.defs#interactionShare",
];

/// The events an `Action` may ask for: more, or less, like an item.
pub const ASKED: &[&str] = &[
    "app.bsky.feed.defs#requestMore",
    "app.bsky.feed.defs#requestLess",
];

/// A feed's generator: the service DID that takes its interactions,
/// whether it does, and the feed's name as its maker gave it.
#[derive(Clone, Debug, PartialEq)]
pub struct Generator {
    pub did: String,
    pub accepts: bool,
    pub name: Option<String>,
}

/// The tool's definition: after the writes, hidden from the model.
pub fn definition() -> Value {
    json!({
        "name": "send_interactions",
        "title": "Send feed interactions",
        "description": "Tell a Bluesky feed's generator what the signed-in person saw, opened, or asked more or less of in it, as Bluesky's app does. Called by the view; needs sign-in.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "feed": { "type": "string", "description": "The feed: the at-uri of its app.bsky.feed.generator record." },
                "interactions": {
                    "type": "array", "minItems": 1, "maxItems": MAX,
                    "items": {
                        "type": "object",
                        "properties": {
                            "item": { "type": "string", "description": "The post's at-uri." },
                            "event": { "type": "string", "enum": EVENTS },
                            "feedContext": { "type": "string", "maxLength": FEED_CONTEXT_MAX },
                            "reqId": { "type": "string", "maxLength": REQ_ID_MAX },
                        },
                        "required": ["item", "event"],
                        "additionalProperties": false,
                    },
                },
            },
            "required": ["feed", "interactions"],
            "additionalProperties": false,
        },
        "annotations": { "title": "Send feed interactions", "readOnlyHint": false,
                         "destructiveHint": false, "idempotentHint": true, "openWorldHint": true },
        "_meta": { "ui": { "visibility": ["app"] } },
    })
}

/// A call's arguments, checked: the feed's at-uri, and 1 to 100
/// interactions, each an item's at-uri, a known event, and the feed's own
/// context and request id for it, of the lengths the lexicon allows.
pub fn checked(arguments: Option<&Value>) -> Result<(String, Vec<Value>), String> {
    let args = Args::of(arguments, &["feed", "interactions"])?;
    let feed = args.required("feed")?.trim();
    if AtUri::parse(feed).map_or(true, |u| u.collection != GENERATOR) {
        return Err(format!(
            "feed must be the at-uri of an {GENERATOR} record: {feed}"
        ));
    }
    let list = match args.0.get("interactions") {
        Some(Value::Array(a)) if (1..=MAX).contains(&a.len()) => a,
        _ => return Err(format!("interactions must be 1 to {MAX} interactions")),
    };
    let mut out = Vec::with_capacity(list.len());
    for (i, v) in list.iter().enumerate() {
        let at = format!("interactions[{i}]");
        let Some(o) = v.as_object() else {
            return Err(format!("{at} must be an object"));
        };
        if let Some(k) = o
            .keys()
            .find(|k| !matches!(k.as_str(), "item" | "event" | "feedContext" | "reqId"))
        {
            return Err(format!("{at}: unknown key {k}"));
        }
        let text = |k: &str| o.get(k).and_then(Value::as_str);
        if !text("item").is_some_and(|u| AtUri::parse(u).is_ok()) {
            return Err(format!("{at}.item must be a record's at-uri"));
        }
        if !text("event").is_some_and(|e| EVENTS.contains(&e)) {
            return Err(format!(
                "{at}.event must be one of app.bsky.feed.defs#{}",
                EVENTS
                    .iter()
                    .filter_map(|e| e.split_once('#').map(|(_, n)| n))
                    .collect::<Vec<_>>()
                    .join(", #")
            ));
        }
        for (k, max) in [("feedContext", FEED_CONTEXT_MAX), ("reqId", REQ_ID_MAX)] {
            match o.get(k) {
                None => {}
                Some(Value::String(s)) if s.len() <= max => {}
                Some(_) => return Err(format!("{at}.{k} must be a string of at most {max} bytes")),
            }
        }
        out.push(v.clone());
    }
    Ok((feed.to_string(), out))
}

/// A generator's view as the AppView gives it: its DID, whether it takes
/// interactions, and its display name, on one line.
fn generator_of(answer: &Value) -> Result<Generator, String> {
    let view = &answer["view"];
    let did = view["did"]
        .as_str()
        .filter(|d| atproto::syntax::is_did(d))
        .ok_or("The feed's generator has no service DID")?;
    Ok(Generator {
        did: did.to_string(),
        accepts: view["acceptsInteractions"] == Value::Bool(true),
        name: view["displayName"]
            .as_str()
            .map(|n| crate::summary::one_line(n, 64))
            .filter(|n| !n.is_empty()),
    })
}

impl Hud {
    /// A feed's generator, from the AppView, as `caller`: kept an hour.
    pub async fn feed_generator(
        &self,
        caller: Caller<'_>,
        feed: &str,
    ) -> Result<Generator, Refusal> {
        if let Some(g) = self.generators.get(&feed.to_string()) {
            return Ok(g);
        }
        let pairs = [("feed".to_string(), feed.to_string())];
        let answer = match caller {
            Caller::Account(a) => {
                let got = self
                    .pds_call(a, GET_GENERATOR, &pairs, None, Some(APPVIEW))
                    .await?;
                if got.status != 200 {
                    return Err(match error_name(&got.body) {
                        Some(e) => format!(
                            "The feed's generator could not be read: {e} ({})",
                            got.status
                        ),
                        None => format!("The feed's generator could not be read ({})", got.status),
                    }
                    .into());
                }
                serde_json::from_slice(&got.body)
                    .map_err(|_| "The feed's generator could not be read".to_string())?
            }
            Caller::Public => {
                let service = Service::parse(APPVIEW)?;
                let endpoint = self.service_endpoint(&service).await?;
                self.call_query(caller, &endpoint, &service, GET_GENERATOR, &pairs)
                    .await?
            }
        };
        let g = generator_of(&answer)?;
        self.generators.put(feed.to_string(), g.clone(), KEEP);
        Ok(g)
    }

    /// A tile's title where its call names a feed by at-uri (`query`
    /// `app.bsky.feed.getFeed`): the feed's own name, from the AppView as no
    /// one (a feed generator's record is public), else none.
    pub async fn feed_title(&self, tool: &str, arguments: &Value) -> Option<String> {
        if tool != "query" || arguments["method"] != "app.bsky.feed.getFeed" {
            return None;
        }
        let feed = arguments["params"]["feed"]
            .as_str()
            .filter(|f| f.starts_with("at://"))?;
        self.feed_generator(Caller::Public, feed).await.ok()?.name
    }

    pub(crate) async fn send_interactions_tool(
        &self,
        arguments: Option<&Value>,
        account: Option<&Account>,
    ) -> Result<Output, Refusal> {
        let Some(account) = account else {
            return Err(Refusal::SignIn);
        };
        let (feed, interactions) = checked(arguments)?;
        let g = self.feed_generator(Caller::Account(account), &feed).await?;
        if !g.accepts {
            return Ok(Output {
                text: format!("{feed} doesn't take interactions; none sent."),
                structured: json!({ "sent": 0, "reason": NOT_TAKEN }),
                meta: json!({}),
            });
        }
        let n = interactions.len();
        let proxy = format!("{}#{FEED_GENERATOR}", g.did);
        let input = json!({ "feed": feed, "interactions": interactions });
        let got = self
            .pds_call(account, SEND, &[], Some(&input), Some(&proxy))
            .await?;
        if got.status != 200 {
            return Err(match error_name(&got.body).as_deref() {
                Some("ScopeMissingError") => {
                    let scope = format!("rpc:{SEND}?aud={}%23{FEED_GENERATOR}", g.did);
                    self.scope_refused(account, &scope).await
                }
                Some(e) => {
                    format!("{} refused the interactions: {e} ({})", g.did, got.status).into()
                }
                None => format!("{} refused the interactions ({})", g.did, got.status).into(),
            });
        }
        // What went, by kind (`interactionSeen` ×6, `requestLess` ×1), so a
        // batch can be told from a button press; never the items.
        let mut kinds: std::collections::BTreeMap<&str, usize> = Default::default();
        for i in &interactions {
            let event = i["event"].as_str().unwrap_or_default();
            *kinds
                .entry(event.rsplit('#').next().unwrap_or(event))
                .or_default() += 1;
        }
        let kinds: Vec<String> = kinds.iter().map(|(k, n)| format!("{k}×{n}")).collect();
        tracing::info!(to = %g.did, sent = n, events = %kinds.join(" "), "interactions sent");
        Ok(Output {
            text: format!(
                "Sent {} to {}.",
                crate::summary::count(
                    n as u64,
                    &["interaction".to_string(), "interactions".to_string()]
                ),
                g.did
            ),
            structured: json!({ "sent": n }),
            meta: json!({}),
        })
    }
}

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

    const FEED: &str = "at://did:plc:3guzzweuqraryl3rdkimjamk/app.bsky.feed.generator/for-you";

    #[test]
    fn arguments_checked() {
        let seen = |item: Value| {
            json!({ "feed": FEED, "interactions": [{ "item": item,
                "event": "app.bsky.feed.defs#interactionSeen", "feedContext": "c", "reqId": "r" }] })
        };
        let (feed, list) =
            checked(Some(&seen(json!("at://did:plc:a/app.bsky.feed.post/3k")))).unwrap();
        assert_eq!(feed, FEED);
        assert_eq!(list[0]["feedContext"], "c");
        let err = |v: Value| checked(Some(&v)).unwrap_err();
        assert!(err(seen(json!("https://bsky.app"))).starts_with("interactions[0].item"));
        assert!(
            err(json!({ "feed": "at://did:plc:a/app.bsky.feed.post/1", "interactions": [] }))
                .starts_with("feed must be")
        );
        assert!(
            err(json!({ "feed": FEED, "interactions": [] }))
                .starts_with("interactions must be 1 to 100")
        );
        let many: Vec<Value> = (0..101)
            .map(|_| json!({ "item": "at://did:plc:a/app.bsky.feed.post/3k", "event": EVENTS[0] }))
            .collect();
        assert!(
            err(json!({ "feed": FEED, "interactions": many })).starts_with("interactions must be")
        );
        let one = |i: Value| json!({ "feed": FEED, "interactions": [i] });
        assert!(
            err(one(json!({ "item": "at://did:plc:a/app.bsky.feed.post/3k", "event": "#interactionSeen" })))
                .starts_with("interactions[0].event")
        );
        assert!(
            err(one(
                json!({ "item": "at://did:plc:a/app.bsky.feed.post/3k", "event": EVENTS[6],
                            "feedContext": "x".repeat(2001) })
            ))
            .starts_with("interactions[0].feedContext")
        );
        assert!(
            err(one(
                json!({ "item": "at://did:plc:a/app.bsky.feed.post/3k", "event": EVENTS[6],
                            "reqId": "x".repeat(101) })
            ))
            .starts_with("interactions[0].reqId")
        );
        assert_eq!(
            err(one(
                json!({ "item": "at://did:plc:a/app.bsky.feed.post/3k", "event": EVENTS[6], "extra": 1 })
            )),
            "interactions[0]: unknown key extra"
        );
        assert!(
            err(json!({ "feed": FEED, "interactions": [], "x": 1 }))
                .starts_with("Unknown argument")
        );
    }

    #[test]
    fn generators_read() {
        let g = generator_of(&json!({ "view": { "did": "did:web:foryou.club",
            "acceptsInteractions": true, "displayName": "For\nYou " } }))
        .unwrap();
        assert_eq!(
            g,
            Generator {
                did: "did:web:foryou.club".into(),
                accepts: true,
                name: Some("For You".into()),
            }
        );
        let g = generator_of(&json!({ "view": { "did": "did:web:x.example" } })).unwrap();
        assert!(!g.accepts);
        assert!(generator_of(&json!({ "view": { "did": "not a did" } })).is_err());
    }

    #[test]
    fn the_definition() {
        let d = definition();
        assert_eq!(d["_meta"]["ui"]["visibility"], json!(["app"]));
        assert_eq!(d["annotations"]["idempotentHint"], json!(true));
        assert_eq!(d["annotations"]["readOnlyHint"], json!(false));
        assert_eq!(d["inputSchema"]["additionalProperties"], json!(false));
    }

    #[test]
    fn interactions_are_objects() {
        let args =
            json!({ "feed": FEED, "interactions": ["at://did:plc:a/app.bsky.feed.post/3k"] });
        assert_eq!(
            checked(Some(&args)).unwrap_err(),
            "interactions[0] must be an object"
        );
    }

    /// A feed generator's view, or its refusal, as the feed's rkey says.
    async fn generator(
        axum::extract::Query(q): axum::extract::Query<std::collections::HashMap<String, String>>,
    ) -> axum::response::Response {
        use axum::http::StatusCode;
        use axum::response::IntoResponse;
        match q["feed"].rsplit('/').next().unwrap() {
            "named" => (StatusCode::BAD_REQUEST, r#"{"error":"NotFound"}"#).into_response(),
            "bare" => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
            "text" => "nope".into_response(),
            _ => axum::Json(json!({ "view": { "did": "did:web:fg.test",
                "acceptsInteractions": true, "displayName": "Picks" } }))
            .into_response(),
        }
    }

    /// What the generator answers interactions sent, as their first's
    /// feed context says.
    async fn send(axum::Json(input): axum::Json<Value>) -> axum::response::Response {
        use axum::http::StatusCode;
        use axum::response::IntoResponse;
        match input["interactions"][0]["feedContext"].as_str().unwrap() {
            "scope" => (StatusCode::FORBIDDEN, r#"{"error":"ScopeMissingError"}"#).into_response(),
            "named" => (StatusCode::BAD_REQUEST, r#"{"error":"Busy"}"#).into_response(),
            _ => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
        }
    }

    fn feed(rkey: &str) -> String {
        format!("at://did:plc:3guzzweuqraryl3rdkimjamk/app.bsky.feed.generator/{rkey}")
    }

    #[tokio::test]
    async fn generators_and_sends_refused_in_a_line() {
        let app =
            axum::Router::new().route("/xrpc/{method}", axum::routing::get(generator).post(send));
        let pds = crate::tests::serve(app).await;
        let (hud, account) = crate::tests::signed_in("http://127.0.0.1:1", &pds);
        let sent = |rkey: &str, context: &str| {
            let args = json!({ "feed": feed(rkey), "interactions": [{
                "item": "at://did:plc:a/app.bsky.feed.post/3k", "event": EVENTS[0],
                "feedContext": context }] });
            let (hud, account) = (hud.clone(), account.clone());
            async move {
                let refused = hud
                    .send_interactions_tool(Some(&args), Some(&account))
                    .await;
                refused.err().unwrap()
            }
        };
        let error = |e: &str| Refusal::Error(e.into());
        assert_eq!(
            sent("named", "c").await,
            error("The feed's generator could not be read: NotFound (400)")
        );
        assert_eq!(
            sent("bare", "c").await,
            error("The feed's generator could not be read (500)")
        );
        assert_eq!(
            sent("text", "c").await,
            error("The feed's generator could not be read")
        );
        assert_eq!(
            sent("picks", "scope").await,
            error(
                "Your sign-in does not allow rpc:app.bsky.feed.sendInteractions?aud=did:web:fg.test%23bsky_fg"
            )
        );
        assert_eq!(
            sent("picks", "named").await,
            error("did:web:fg.test refused the interactions: Busy (400)")
        );
        assert_eq!(
            sent("picks", "bare").await,
            error("did:web:fg.test refused the interactions (500)")
        );
    }

    #[tokio::test]
    async fn a_feeds_title_is_its_generators_name() {
        let app = axum::Router::new().route("/xrpc/{method}", axum::routing::get(generator));
        let appview = crate::tests::serve(app).await;
        let hud = crate::tests::hud_with("http://127.0.0.1:1", |_| {});
        let doc = json!({ "id": "did:web:api.bsky.app", "service": [
            { "id": "#bsky_appview", "type": "BskyAppView", "serviceEndpoint": appview }] });
        hud.docs.put(
            "did:web:api.bsky.app".into(),
            Ok(std::sync::Arc::new(doc)),
            Duration::from_secs(60),
        );
        let title = |tool: &'static str, feed: String| {
            let hud = hud.clone();
            let args = json!({ "method": "app.bsky.feed.getFeed", "params": { "feed": feed } });
            async move { hud.feed_title(tool, &args).await }
        };
        assert_eq!(
            title("query", feed("picks")).await.as_deref(),
            Some("Picks")
        );
        assert_eq!(title("query", "picks".into()).await, None);
        assert_eq!(title("open", feed("picks")).await, None);
        // A generator that cannot be read has no name to give.
        assert_eq!(title("query", feed("bare")).await, None);
    }
}