~ 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
351 lines · 15.1 KB Raw History
//! Procedures a person calls from a view (`call_procedure`, hidden from the
//! model): an `Action`'s `call`, a `Messages`' `send`, as a chat message;
//! and an app's client registering a device for push, as its app file's
//! `push` says (`operator`). An `Action`'s or select's `deletes` comes
//! through it too, as the call the clients make already: its query asked
//! for a deletion plan, committed at the account's PDS at once
//! (`Hud::delete_planned`).
//! The `query` tool calls queries alone; this is how a view writes beyond
//! records, and only as a trusted view (bundled, or the operator's,
//! `operator`) says it may: a procedure is sent only if a trusted view, or
//! an operator's app file's push, calls that method of that service
//! (`view::bundled_call`), so neither an inline view nor anyone who
//! reaches the tool can send what no trusted view or app file does. The
//! input is checked against the procedure's lexicon
//! (resolved as any is, and bundled for the procedures trusted views call,
//! the operator's checked against them as HUD starts) and goes through the
//! account's PDS,
//! proxied to the service (`atproto-proxy`), so the PDS signs for the
//! account; the answer is checked against the lexicon's output, its blobs
//! pointed at the proxy as a private answer's are. Neither input nor
//! answer is logged, nor said in the tool's `content`.

use crate::Hud;
use crate::net::Fetched;
use crate::oauth::Account;
use crate::pds::error_name;
use crate::tools::{Args, Output, Refusal};
use crate::xrpc::{
    Service, account_answer, lexicons_for, output_problem, own_doc, rewrite_response, video_urls,
};
use serde_json::{Map, Value, json};

/// The tool's definition: after the writes, hidden from the model.
pub fn definition() -> Value {
    json!({
        "name": "call_procedure",
        "title": "Call a procedure",
        "description": "Call an XRPC procedure of a service as the signed-in person, through their PDS, as a bundled view calls it (a chat message sent, a chat marked read); or, where a bundled view deletes what a query plans, ask that query with input as its params and delete the records it plans from their repository, all at once (a gallery with its photos, or an account's data a part at a time). Called by the view; needs sign-in.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "method": { "type": "string", "description": "The procedure's NSID." },
                "service": { "type": "string", "description": "The service: a DID and its service's #fragment, as did:web:api.bsky.chat#bsky_chat." },
                "input": { "type": "object", "description": "Its input, as its lexicon takes it." },
            },
            "required": ["method", "service"],
            "additionalProperties": false,
        },
        "annotations": { "title": "Call a procedure", "readOnlyHint": false,
                         "destructiveHint": false, "idempotentHint": false, "openWorldHint": true },
        "_meta": { "ui": { "visibility": ["app"] } },
    })
}

/// A lexicon document's main def, if it is a procedure taking JSON or
/// nothing; else why it cannot be called.
pub fn procedure_def<'a>(method: &str, doc: &'a Value) -> Result<&'a Value, String> {
    let main = &doc["defs"]["main"];
    match main["type"].as_str() {
        Some("procedure") => {}
        Some(other) => return Err(format!("{method} is a {other}, not a procedure")),
        None => return Err(format!("{method} is not a method")),
    }
    match main["input"]["encoding"].as_str() {
        None | Some("application/json") => Ok(main),
        Some(other) => Err(format!("{method} takes {other}, not JSON")),
    }
}

/// A call's arguments, checked: the method, the service, and the input (an
/// object, empty if left out); and that a bundled view calls it, or, where
/// the last is true, deletes what it plans (`deletes`, the input its
/// params).
pub fn checked(
    arguments: Option<&Value>,
) -> Result<(String, Service, Map<String, Value>, bool), String> {
    let args = Args::of(arguments, &["method", "service", "input"])?;
    let method = args.required("method")?.trim();
    if !atproto::syntax::is_nsid(method) {
        return Err(format!("Not a method's NSID: {method}"));
    }
    let service = Service::parse(args.required("service")?)?;
    let input = match args.0.get("input") {
        None | Some(Value::Null) => Map::new(),
        Some(Value::Object(i)) => i.clone(),
        Some(_) => return Err("input must be an object".into()),
    };
    let name = service.name();
    let deletes = crate::view::bundled_deletes(method, &name);
    if !deletes && !crate::view::bundled_call(method, &name) {
        return Err(format!(
            "{method} of {name} is no procedure a bundled view calls"
        ));
    }
    Ok((method.to_string(), service, input, deletes))
}

/// A procedure's answer, as its def says it answers: nothing if it names
/// no output, else a JSON object, if `body` is one.
fn answer(def: &Value, body: &[u8]) -> Option<Value> {
    if def["output"]["schema"].is_null() {
        return Some(Value::Null);
    }
    serde_json::from_slice(body).ok().filter(Value::is_object)
}

impl Hud {
    pub(crate) async fn call_procedure_tool(
        &self,
        arguments: Option<&Value>,
        account: Option<&Account>,
    ) -> Result<Output, Refusal> {
        let Some(account) = account else {
            return Err(Refusal::SignIn);
        };
        let (method, service, input, deletes) = checked(arguments)?;
        if deletes {
            return self.delete_planned(account, &method, &service, input).await;
        }
        let input = Value::Object(input);
        let docs = self.lexicon_docs(&method).await;
        let doc = own_doc(&method, &docs)?;
        let def = procedure_def(&method, doc)?;
        let lexicons = lexicons_for(&method, &docs);
        lexicons
            .validate_input(&method, &input)
            .map_err(|e| format!("The input does not match {method}: {e}"))?;
        let got = self
            .pds_write(account, &method, &input, Some(&service.name()))
            .await?;
        if got.status != 200 {
            return Err(self
                .service_refused(account, &got, &method, &service.name())
                .await);
        }
        let mut output = answer(def, &got.body).ok_or_else(|| {
            format!(
                "{} answered {method} with something that is not JSON",
                service.did
            )
        })?;
        if let Some(problem) = output_problem(&lexicons, &method, def, &output) {
            return Err(format!("The answer does not match {method}: {problem}").into());
        }
        rewrite_response(
            &mut output,
            self.config.blob_urls(),
            account_answer(&service),
        );
        video_urls(&mut output, &self.config.public_origin);
        tracing::info!(%method, service = %service.name(), "procedure called");
        Ok(Output {
            text: format!("Called {method}."),
            structured: json!({ "output": output }),
            meta: json!({}),
        })
    }

    /// A service's refusal of `method`, asked as the account through its
    /// PDS, in one line naming no more of its words than its error's name;
    /// one for want of scope, as `scope_refused` answers it.
    pub(crate) async fn service_refused(
        &self,
        account: &Account,
        got: &Fetched,
        method: &str,
        service: &str,
    ) -> Refusal {
        let did = service.split('#').next().unwrap_or_default();
        match error_name(&got.body).as_deref() {
            Some("ScopeMissingError") => {
                let aud = service.replace('#', "%23");
                self.scope_refused(account, &format!("rpc:{method}?aud={aud}"))
                    .await
            }
            Some(e) => format!("{did} refused {method}: {e} ({})", got.status).into(),
            None => format!("{did} refused {method} ({})", got.status).into(),
        }
    }
}

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

    const CHAT: &str = "did:web:api.bsky.chat#bsky_chat";

    #[test]
    fn only_what_a_bundled_view_calls() {
        let (method, service, input, deletes) = checked(Some(&json!({
            "method": "chat.bsky.convo.sendMessage", "service": CHAT,
            "input": { "convoId": "c", "message": { "text": "hi" } } })))
        .unwrap();
        assert_eq!(
            (method.as_str(), service.name().as_str(), deletes),
            ("chat.bsky.convo.sendMessage", CHAT, false)
        );
        assert_eq!(input["message"]["text"], "hi");
        // A query whose deletion plan a trusted view deletes (Grain's).
        let (method, _, input, deletes) = checked(Some(&json!({
            "method": "social.grain.gallery.getDeletionPlan",
            "service": "did:web:grain.social#grain_appview" })))
        .unwrap();
        assert_eq!(
            (method.as_str(), input.len(), deletes),
            ("social.grain.gallery.getDeletionPlan", 0, true)
        );
        let err = |v: Value| checked(Some(&v)).unwrap_err();
        // A procedure no bundled view calls, or one it calls of another service.
        assert_eq!(
            err(json!({ "method": "com.atproto.server.deleteAccount", "service": CHAT })),
            "com.atproto.server.deleteAccount of did:web:api.bsky.chat#bsky_chat is no procedure a bundled view calls"
        );
        assert!(
            err(json!({ "method": "chat.bsky.convo.sendMessage", "service": "did:web:evil.example#bsky_chat" }))
                .ends_with("is no procedure a bundled view calls")
        );
        assert_eq!(
            err(json!({ "method": "chat.bsky.convo.sendMessage", "service": CHAT, "input": [] })),
            "input must be an object"
        );
        assert_eq!(
            err(json!({ "method": "x", "service": CHAT })),
            "Not a method's NSID: x"
        );
    }

    /// An operator's app file's push call (Grain's `registerPush`) is sent
    /// as a view's call is: through the account's PDS to its service, its
    /// input held to its lexicon first.
    #[tokio::test]
    async fn an_apps_push_is_sent() {
        let grain = "did:web:grain.social#grain_appview";
        let answer = move |headers: axum::http::HeaderMap, axum::Json(input): axum::Json<Value>| async move {
            assert_eq!(headers["atproto-proxy"], grain);
            assert_eq!(input["token"], "ab12");
            axum::Json(json!({}))
        };
        let app = axum::Router::new().route("/xrpc/{method}", axum::routing::post(answer));
        let pds = crate::tests::serve(app).await;
        let (hud, account) = crate::tests::signed_in("http://127.0.0.1:1", &pds);
        let mut args = json!({ "method": "social.grain.notification.registerPush", "service": grain,
            "input": { "serviceDid": "did:web:grain.social", "token": "ab12",
                       "platform": "ios", "appId": "social.grain.grain" } });
        let sent = hud.call_procedure_tool(Some(&args), Some(&account)).await;
        assert_eq!(sent.unwrap().structured, json!({ "output": {} }));
        args["input"]["platform"] = json!(5);
        let refused = hud.call_procedure_tool(Some(&args), Some(&account)).await;
        assert!(
            matches!(&refused, Err(Refusal::Error(e)) if e.starts_with("The input does not match social.grain.notification.registerPush")),
            "{refused:?}"
        );
    }

    #[test]
    fn procedures_alone() {
        let doc = |main: Value| json!({ "defs": { "main": main } });
        assert!(procedure_def("a.b.c", &doc(json!({ "type": "procedure" }))).is_ok());
        assert_eq!(
            procedure_def("a.b.c", &doc(json!({ "type": "query" }))).unwrap_err(),
            "a.b.c is a query, not a procedure"
        );
        assert_eq!(
            procedure_def(
                "a.b.c",
                &doc(json!({ "type": "procedure", "input": { "encoding": "*/*" } }))
            )
            .unwrap_err(),
            "a.b.c takes */*, not JSON"
        );
        assert_eq!(
            procedure_def("a.b.c", &json!({})).unwrap_err(),
            "a.b.c is not a method"
        );
    }

    #[test]
    fn answers_as_the_def_says() {
        let object = json!({ "output": { "schema": { "type": "object" } } });
        assert_eq!(answer(&object, br#"{"a":1}"#), Some(json!({ "a": 1 })));
        assert_eq!(answer(&object, b"[]"), None);
        assert_eq!(answer(&object, b"<html>"), None);
        // A procedure that names no output answers nothing, whatever it sent.
        assert_eq!(
            answer(&json!({ "output": {} }), b"<html>"),
            Some(Value::Null)
        );
    }

    #[tokio::test]
    async fn refusals_of_a_procedure_in_a_line() {
        use axum::http::StatusCode;
        use axum::response::IntoResponse;
        let answer = |axum::Json(input): axum::Json<Value>| async move {
            match input["convoId"].as_str().unwrap() {
                "scope" => {
                    (StatusCode::FORBIDDEN, r#"{"error":"ScopeMissingError"}"#).into_response()
                }
                "named" => (StatusCode::BAD_REQUEST, r#"{"error":"InvalidConvo"}"#).into_response(),
                "bare" => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
                "text" => "nope".into_response(),
                _ => axum::Json(json!({ "convo": 5 })).into_response(),
            }
        };
        let app = axum::Router::new().route("/xrpc/{method}", axum::routing::post(answer));
        let pds = crate::tests::serve(app).await;
        let (hud, account) = crate::tests::signed_in("http://127.0.0.1:1", &pds);
        let read = |convo: &str| {
            let args = json!({ "method": "chat.bsky.convo.updateRead", "service": CHAT,
                               "input": { "convoId": convo } });
            let (hud, account) = (hud.clone(), account.clone());
            async move {
                let refused = hud.call_procedure_tool(Some(&args), Some(&account)).await;
                refused.err().unwrap()
            }
        };
        let chat = "did:web:api.bsky.chat";
        let method = "chat.bsky.convo.updateRead";
        let error = |e: String| Refusal::Error(e);
        assert_eq!(
            read("scope").await,
            error(format!(
                "Your sign-in does not allow rpc:{method}?aud={chat}%23bsky_chat"
            ))
        );
        assert_eq!(
            read("named").await,
            error(format!("{chat} refused {method}: InvalidConvo (400)"))
        );
        assert_eq!(
            read("bare").await,
            error(format!("{chat} refused {method} (500)"))
        );
        assert_eq!(
            read("text").await,
            error(format!(
                "{chat} answered {method} with something that is not JSON"
            ))
        );
        let prefix = format!("The answer does not match {method}: ");
        assert!(matches!(read("wrong").await, Refusal::Error(e) if e.starts_with(&prefix)));
    }

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