~ 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
1113 lines · 40.5 KB Raw History
//! HUD's methods, `/xrpc/place.hud.*`, each as its lexicon in `schemas/`
//! says, as an atproto appview answers them: a query by `GET`, its params
//! in the query string; a procedure by `POST`, its input a JSON object of
//! at most 256 KiB (`previewView`'s, which carries an answer read before,
//! 4 MiB), but `uploadBlob`'s, an image's bytes, at most 2,000,000, sent
//! on to the caller's PDS. Input is checked against the lexicon, then by
//! HUD's own rules, before anything is done; a name the lexicon does not
//! take is refused. A failure is `{error, message}`, its error one the
//! method's lexicon names: `NotFound`, `Forbidden`, `InvalidRequest`,
//! `LimitReached`, `AuthRequired`, `UpstreamFailure`; a method HUD has
//! not, `MethodNotImplemented` (501); the request's line names it too
//! (`telemetry::Cause`). `deleteAccountData` called with the cookie
//! answers as `POST /workspace/signout` does: the browser goes on as the
//! account it used last before, else signed out.
//!
//! The workspace's methods are there with sign-in on alone. A caller is
//! the account of the workspace's web session (its cookie,
//! `hud_session`), or of a HUD access token as `Bearer`, as MCP clients
//! have: what an app of the person's or the bridge calls with. A
//! procedure called with the cookie must also say `X-HUD: 1` and come from
//! the server's own origin (`Origin`), else `403`: no other site's page can
//! make one. A token that is not one HUD gave is `401` with the
//! `invalid_token` challenge. `getLogs` is the operators' alone
//! (`HUD_OPERATOR_DIDS`, `hud_core::logs`).
//!
//! Anyone's, sign-in on or off, reading no session: `searchActors`, a
//! sign-in's suggestions, and the playground's (`crate::playground`):
//! `getPlayground`, and `previewView`, which calls as the account where a
//! session is good, else as no one.
//!
//! `getWorkspaceEvents` answers server-sent events: every change to the
//! person's open canvases, who is on them, and their workspace's changes,
//! as `place.hud.defs` types them, until their session ends.

use crate::mcp::{bearer, tool_result};
use crate::workspace::{cookie, same_origin};
use axum::Router;
use axum::body::Body;
use axum::extract::{Path, RawQuery, State};
use axum::http::{HeaderMap, Method, StatusCode, header};
use axum::response::sse::{Event as SseEvent, KeepAlive, Sse};
use axum::response::{IntoResponse, Response};
use axum::routing::any;
use hud_core::Hud;
use hud_core::canvas::{
    Beside, By, Notice, Op, Refused, Role, Watch, Who, checked_arguments, checked_id, checked_name,
    checked_title, checked_tool, checked_width,
};
use hud_core::kit::Kit;
use hud_core::oauth::Account;
use hud_core::tools::Refusal;
use serde_json::{Map, Value as Json, json};
use std::collections::VecDeque;
use std::convert::Infallible;
use std::sync::{Arc, LazyLock};
use std::time::{Duration, Instant};

/// The methods' namespace.
const NS: &str = "place.hud.";
/// The most of a procedure's input read.
const MAX_BODY: usize = 256 * 1024;
/// The most of `previewView`'s input read: a view and the answer it
/// draws over, which a feed's page with its joins makes large.
const PREVIEW_BODY: usize = 4 * 1024 * 1024;
/// The methods an instance serving its operator's apps alone
/// (`HUD_WORKSPACE=off`) has: a sign-in's suggestions, a composer's
/// pictures, the operators' lines, and what HUD keeps of a person. The
/// rest are the workspace's and the playground's.
const APPS_ALONE: [&str; 5] = [
    "searchActors",
    "uploadBlob",
    "getLogs",
    "getAccountData",
    "deleteAccountData",
];
/// How often an idle event stream says it is there.
const PING: Duration = Duration::from_secs(25);
/// How often an event stream checks that its session goes on.
const RECHECK: Duration = Duration::from_secs(60);
/// A page of `listCanvases`, by default and at most.
const PAGE: usize = 50;
const PAGE_MAX: usize = 100;

/// HUD's own lexicons, which the methods' input is checked against.
static LEXICONS: LazyLock<atproto::lexicon::Lexicons> = LazyLock::new(|| {
    atproto::lexicon::Lexicons::new(
        hud_core::lexicon::all_bundled()
            .filter(|d| d["id"].as_str().is_some_and(|id| id.starts_with(NS)))
            .map(|d| (**d).clone()),
    )
});

/// The methods' route.
pub fn routes() -> Router<Arc<Hud>> {
    Router::new().route("/xrpc/{method}", any(endpoint))
}

/// The route a request to `path` is logged and counted by: one of HUD's
/// methods by its own path, as `/xrpc/place.hud.getCanvas`, so each is
/// told apart; any other, by the route's `template`.
pub(crate) fn route(template: &str, path: &str) -> String {
    let method = path.strip_prefix("/xrpc/").unwrap_or_default();
    let named = template == "/xrpc/{method}"
        && method.starts_with(NS)
        && LEXICONS
            .def(method)
            .is_some_and(|d| matches!(d["type"].as_str(), Some("query" | "procedure")));
    match named {
        true => path.to_string(),
        false => template.to_string(),
    }
}

/// A failure, as XRPC answers one.
#[derive(Debug)]
pub(crate) struct Failure {
    status: StatusCode,
    error: &'static str,
    message: String,
}

fn fail(status: StatusCode, error: &'static str, message: impl Into<String>) -> Failure {
    Failure {
        status,
        error,
        message: message.into(),
    }
}

fn invalid(message: impl Into<String>) -> Failure {
    fail(StatusCode::BAD_REQUEST, "InvalidRequest", message)
}

impl From<Refused> for Failure {
    fn from(r: Refused) -> Failure {
        match r {
            Refused::Invalid(why) => invalid(why),
            Refused::Forbidden(why) => fail(StatusCode::FORBIDDEN, "Forbidden", why),
            Refused::Limit(why) => fail(StatusCode::BAD_REQUEST, "LimitReached", why),
            // A canvas's id: the methods name canvases by id alone, and only
            // a canvas tool names one by its name.
            Refused::NoCanvas(id) => fail(
                StatusCode::NOT_FOUND,
                "NotFound",
                format!("No canvas {id} of yours"),
            ),
            Refused::NoTile(id) => fail(
                StatusCode::NOT_FOUND,
                "NotFound",
                format!("There is no tile {id} on that canvas"),
            ),
        }
    }
}

impl From<String> for Failure {
    fn from(why: String) -> Failure {
        invalid(why)
    }
}

impl From<hud_core::theme::Refused> for Failure {
    fn from(r: hud_core::theme::Refused) -> Failure {
        match r {
            hud_core::theme::Refused::Invalid(why) => invalid(why),
            hud_core::theme::Refused::NotFound(why) => fail(StatusCode::NOT_FOUND, "NotFound", why),
            // As callTool answers it: the page and the app sign in again.
            hud_core::theme::Refused::SignIn => fail(
                StatusCode::UNAUTHORIZED,
                "AuthRequired",
                "Your sign-in at your PDS ended: sign in again",
            ),
        }
    }
}

impl IntoResponse for Failure {
    fn into_response(self) -> Response {
        // The request's line says which error; for one of this server's
        // own (5xx), why too.
        let cause = match self.status.is_server_error() {
            true => format!("{}: {}", self.error, self.message),
            false => self.error.to_string(),
        };
        let mut r = answer(
            self.status,
            &json!({ "error": self.error, "message": self.message }),
        );
        r.extensions_mut().insert(crate::telemetry::Cause(cause));
        if self.status == StatusCode::UNAUTHORIZED {
            r.headers_mut().insert(
                header::WWW_AUTHENTICATE,
                header::HeaderValue::from_static("Bearer"),
            );
        }
        r
    }
}

impl From<hud_core::logs::Unread> for Failure {
    fn from(u: hud_core::logs::Unread) -> Failure {
        use hud_core::logs::Unread;
        let (status, error) = match &u {
            Unread::Forbidden => (StatusCode::FORBIDDEN, "Forbidden"),
            Unread::NotKept => (StatusCode::NOT_FOUND, "NotFound"),
            Unread::Invalid(_) => (StatusCode::BAD_REQUEST, "InvalidRequest"),
            Unread::Failed(_) => (StatusCode::INTERNAL_SERVER_ERROR, "LogsUnreadable"),
        };
        fail(status, error, u.message())
    }
}

/// A JSON answer, never kept by a cache.
fn answer(status: StatusCode, body: &Json) -> Response {
    (
        status,
        [
            (header::CONTENT_TYPE, "application/json"),
            (header::CACHE_CONTROL, "no-store"),
        ],
        body.to_string(),
    )
        .into_response()
}

/// Who calls: their account, and what they called with, to check it goes
/// on.
struct Caller {
    account: Account,
    proof: Proof,
}

enum Proof {
    Cookie(String),
    Token(String),
}

impl Caller {
    fn who(&self) -> Who<'_> {
        Who {
            did: &self.account.did,
            handle: self.account.handle.as_deref(),
        }
    }

    /// Whether its session goes on.
    fn live(&self, hud: &Hud) -> bool {
        hud.oauth.as_ref().is_some_and(|auth| match &self.proof {
            Proof::Cookie(c) => auth.web_account(c).is_some(),
            Proof::Token(t) => auth.account(t).is_some(),
        })
    }
}

/// The caller a request's token or cookie names; else the refusal.
fn caller(hud: &Hud, headers: &HeaderMap) -> Result<Caller, Failure> {
    let signed_out = || {
        fail(
            StatusCode::UNAUTHORIZED,
            "AuthRequired",
            "Sign in to HUD for this",
        )
    };
    if headers.contains_key(header::AUTHORIZATION) {
        let token = headers
            .get(header::AUTHORIZATION)
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.split_once(' '))
            .map(|(_, t)| t.trim().to_string())
            .unwrap_or_default();
        return match bearer(hud, headers) {
            Ok(Some(account)) => Ok(Caller {
                account,
                proof: Proof::Token(token),
            }),
            _ => Err(fail(
                StatusCode::UNAUTHORIZED,
                "AuthRequired",
                "The token is not one HUD gave, or it expired or was revoked: sign in again",
            )),
        };
    }
    let c = cookie(headers).ok_or_else(signed_out)?;
    let account = hud
        .oauth
        .as_ref()
        .and_then(|a| a.web_account(c))
        .ok_or_else(signed_out)?;
    Ok(Caller {
        account,
        proof: Proof::Cookie(c.to_string()),
    })
}

/// `/xrpc/<method>`: a method of HUD's answered, as the module says.
async fn endpoint(
    State(hud): State<Arc<Hud>>,
    Path(method): Path<String>,
    RawQuery(query): RawQuery,
    http: Method,
    headers: HeaderMap,
    body: Body,
) -> Response {
    let handled = handle(&hud, &method, query.as_deref(), &http, &headers, body).await;
    handled.unwrap_or_else(IntoResponse::into_response)
}

async fn handle(
    hud: &Arc<Hud>,
    method: &str,
    query: Option<&str>,
    http: &Method,
    headers: &HeaderMap,
    body: Body,
) -> Result<Response, Failure> {
    let def = method
        .strip_prefix(NS)
        .and_then(|_| LEXICONS.def(method))
        .filter(|d| matches!(d["type"].as_str(), Some("query" | "procedure")))
        .ok_or_else(|| {
            fail(
                StatusCode::NOT_IMPLEMENTED,
                "MethodNotImplemented",
                format!("HUD has no method {method}"),
            )
        })?;
    let procedure = def["type"] == "procedure";
    let wanted = if procedure { Method::POST } else { Method::GET };
    if *http != wanted {
        return Err(fail(
            StatusCode::METHOD_NOT_ALLOWED,
            "InvalidRequest",
            format!("{method} is called by {wanted}"),
        ));
    }
    let name = &method[NS.len()..];
    if !hud.config.workspace && !APPS_ALONE.contains(&name) {
        return Err(fail(
            StatusCode::NOT_IMPLEMENTED,
            "MethodNotImplemented",
            format!("HUD serves no workspace here: no {method}"),
        ));
    }
    // Suggestions for a sign-in's handle field, for anyone: no session.
    if name == "searchActors" {
        let input = query_params(method, def, query)?;
        let limit = input.get("limit").and_then(Json::as_u64).unwrap_or(6);
        let actors = hud
            .search_actors(need(&input, "q"), limit.clamp(1, 10) as usize)
            .await;
        return Ok(answer(StatusCode::OK, &json!({ "actors": actors })));
    }
    // What the playground starts from, the same for everyone.
    if name == "getPlayground" {
        query_params(method, def, query)?;
        return Ok(answer(StatusCode::OK, playground()));
    }
    // A view drawn for the playground: as the account where one is
    // signed in, else as no one.
    if name == "previewView" {
        let caller = caller(hud, headers).ok();
        if caller
            .as_ref()
            .is_some_and(|c| matches!(c.proof, Proof::Cookie(_)))
        {
            from_page(hud, headers)?;
        }
        let input = procedure_input(method, def, body, PREVIEW_BODY).await?;
        let account = caller.as_ref().map(|c| &c.account);
        return Ok(answer(
            StatusCode::OK,
            &preview(hud, account, &input).await?,
        ));
    }
    // The rest are the workspace's, which sign-in off has none of.
    if hud.oauth.is_none() {
        return Err(fail(
            StatusCode::NOT_IMPLEMENTED,
            "MethodNotImplemented",
            format!("HUD has sign-in off: no {method}"),
        ));
    }
    let caller = caller(hud, headers)?;
    // An image's bytes, for `uploadBlob`; else the input, as JSON.
    let (input, image) = if procedure {
        if let Proof::Cookie(_) = caller.proof {
            from_page(hud, headers)?;
        }
        match name {
            "uploadBlob" => (Map::new(), Some(body)),
            _ => (procedure_input(method, def, body, MAX_BODY).await?, None),
        }
    } else {
        (query_params(method, def, query)?, None)
    };
    if name == "getWorkspaceEvents" {
        return Ok(events(hud.clone(), caller).await);
    }
    let mut out = match image {
        Some(body) => upload(hud, &caller, headers, body).await,
        None => call(hud, &caller, name, &input).await,
    };
    // The page's other accounts, which only its cookies name.
    if let (Ok(v), "getWorkspace", Proof::Cookie(_)) = (&mut out, name, &caller.proof) {
        v["accounts"] = json!(crate::workspace::accounts(hud, headers));
    }
    let mut r = answer(StatusCode::OK, &out?);
    // Its sessions ended, the page goes on as sign-out leaves it.
    if let ("deleteAccountData", Proof::Cookie(_)) = (name, &caller.proof) {
        crate::workspace::moved_on(hud, headers, &mut r).await;
    }
    Ok(r)
}

/// A query's params from its query string, as its lexicon types them,
/// checked: one it does not declare is refused.
fn query_params(
    method: &str,
    def: &Json,
    query: Option<&str>,
) -> Result<Map<String, Json>, Failure> {
    let pairs: Vec<(String, String)> =
        url::form_urlencoded::parse(query.unwrap_or_default().as_bytes())
            .map(|(k, v)| (k.into_owned(), v.into_owned()))
            .collect();
    let declared = def["parameters"]["properties"].as_object();
    if let Some((k, _)) = pairs
        .iter()
        .find(|(k, _)| declared.is_none_or(|d| !d.contains_key(k)))
    {
        return Err(invalid(format!("{k} is not a parameter of {method}")));
    }
    let params = LEXICONS.query_params(method, &pairs);
    LEXICONS
        .validate_params(method, &params)
        .map_err(|e| invalid(e.to_string()))?;
    Ok(params)
}

/// A procedure's input: a JSON object of at most `max` bytes, valid for its
/// lexicon, naming nothing it does not declare.
async fn procedure_input(
    method: &str,
    def: &Json,
    body: Body,
    max: usize,
) -> Result<Map<String, Json>, Failure> {
    let bytes = axum::body::to_bytes(body, max).await.map_err(|_| {
        fail(
            StatusCode::PAYLOAD_TOO_LARGE,
            "InvalidRequest",
            format!("The input is too large: at most {} KiB", max / 1024),
        )
    })?;
    let Ok(Json::Object(input)) = serde_json::from_slice::<Json>(&bytes) else {
        return Err(invalid("The input must be a JSON object"));
    };
    let declared = def["input"]["schema"]["properties"].as_object();
    if let Some(k) = input
        .keys()
        .find(|k| declared.is_none_or(|d| !d.contains_key(k.as_str())))
    {
        return Err(invalid(format!("{k} is not an input of {method}")));
    }
    LEXICONS
        .validate_input(method, &Json::Object(input.clone()))
        .map_err(|e| invalid(e.to_string()))?;
    Ok(input)
}

/// A procedure called with the cookie: only from the server's own page,
/// which says `X-HUD: 1`, from its own origin.
fn from_page(hud: &Hud, headers: &HeaderMap) -> Result<(), Failure> {
    let said = headers.get("x-hud").and_then(|v| v.to_str().ok()) == Some("1");
    if said && same_origin(hud, headers) {
        return Ok(());
    }
    Err(fail(
        StatusCode::FORBIDDEN,
        "InvalidRequest",
        "Only the workspace's own page may do this, with X-HUD: 1",
    ))
}

/// `getPlayground`: the bundled views a read tool draws (not app pages),
/// each as a view given inline may be (`view::inline_copy`) with the app
/// it names, the component catalog and HUD's themes, made once.
fn playground() -> &'static Json {
    static MADE: LazyLock<Json> = LazyLock::new(|| {
        let views: Vec<Json> = hud_core::view::bundled()
            .iter()
            .filter(|b| b.view.page.is_none())
            .map(|b| {
                json!({ "name": b.id, "app": b.view.app.clone().unwrap_or_default(),
                        "view": hud_core::view::inline_copy(&b.view.doc) })
            })
            .collect();
        json!({ "views": views, "catalog": hud_core::catalog::to_json(),
                "themes": hud_core::theme::all() })
    });
    &MADE
}

/// `previewView`: the inline view's problems, every one, where it has
/// any; else drawn again over the answer given (`Hud::redraw`); else the
/// call made afresh, its result as `/mcp` gives it, logged as a tool
/// call is. Signed out, a call that needs an account is the result's
/// error.
async fn preview(
    hud: &Hud,
    account: Option<&Account>,
    input: &Map<String, Json>,
) -> Result<Json, Failure> {
    let tool = need(input, "tool");
    if !matches!(tool, "list_records" | "get_record" | "query") {
        return Err(invalid(format!(
            "{tool} draws no view: list_records, get_record and query do"
        )));
    }
    let arguments = input.get("arguments");
    let doc = arguments
        .and_then(|a| a.get("view"))
        .filter(|v| v.is_object())
        .ok_or_else(|| invalid("The arguments give no view: give it as their view"))?;
    if let Err(problems) = hud_core::view::parse(doc, false) {
        let problems: Vec<Json> = problems
            .iter()
            .map(|p| {
                let (at, message) = p.split_once(": ").unwrap_or(("view", p));
                json!({ "at": at, "message": message })
            })
            .collect();
        return Ok(json!({ "problems": problems }));
    }
    // The playground draws with the web renderer, as current as HUD.
    let kit = Kit::current("playground");
    if let Some(answer) = input.get("answer") {
        let mut ui = hud
            .redraw(tool, arguments, answer, account)
            .await
            .map_err(invalid)?;
        hud_core::kit::fit_tree(&mut ui, &kit);
        return Ok(json!({ "ui": ui }));
    }
    let started = Instant::now();
    let answered = match hud.call_tool(tool, arguments, account).await {
        Some(Ok(mut out)) => {
            hud_core::kit::fit(&mut out.meta, &kit);
            Ok(out)
        }
        Some(Err(Refusal::Error(e))) => Err(e),
        // Asked for an account: the tool is one of the three, all known.
        _ => Err("Sign in to HUD to read this".to_string()),
    };
    hud_core::telemetry::tool(&hud_core::telemetry::Tool {
        name: tool,
        did: account.map(|a| a.did.as_str()),
        error: answered.as_ref().err().map(String::as_str),
        reason: None,
        took: started.elapsed(),
        kit: kit.said.as_deref(),
    });
    Ok(json!({ "result": tool_result(answered, false) }))
}

/// `uploadBlob`: an image (`Content-Type: image/*`, its bytes a JPEG, PNG,
/// WebP or HEIC) of at most `BLOB_MAX` bytes sent to the caller's PDS as
/// their blob, the blob ref it answered; the bytes never logged.
async fn upload(
    hud: &Hud,
    caller: &Caller,
    headers: &HeaderMap,
    body: Body,
) -> Result<Json, Failure> {
    use hud_core::pds::{BLOB_MAX, image_type};
    let said_image = headers
        .get(header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .is_some_and(|t| t.trim().to_ascii_lowercase().starts_with("image/"));
    let bytes = axum::body::to_bytes(body, BLOB_MAX).await.map_err(|_| {
        fail(
            StatusCode::PAYLOAD_TOO_LARGE,
            "BlobTooLarge",
            "The image is too large: at most 2,000,000 bytes",
        )
    })?;
    let mime = image_type(&bytes)
        .filter(|_| said_image)
        .ok_or_else(|| invalid("Send a JPEG, PNG, WebP or HEIC image, as image/*"))?;
    match hud.upload_blob(&caller.account, mime, bytes).await {
        Ok(blob) => Ok(json!({ "blob": blob })),
        Err(Refusal::SignIn) if hud.behind(&caller.account).await => Err(fail(
            StatusCode::BAD_GATEWAY,
            "UpstreamFailure",
            hud_core::oauth::SIGN_IN_AGAIN,
        )),
        Err(Refusal::SignIn) => Err(fail(
            StatusCode::UNAUTHORIZED,
            "AuthRequired",
            "Your sign-in at your PDS ended: sign in again",
        )),
        Err(Refusal::Error(why)) => Err(fail(StatusCode::BAD_GATEWAY, "UpstreamFailure", why)),
    }
}

/// A string field of the input, if given.
fn text<'a>(input: &'a Map<String, Json>, k: &str) -> Option<&'a str> {
    input.get(k).and_then(Json::as_str)
}

/// A required string field: the lexicon has checked it is there, a string,
/// before the method is answered.
fn need<'a>(input: &'a Map<String, Json>, k: &str) -> &'a str {
    text(input, k).unwrap_or_default()
}

/// An id field, checked.
fn id(input: &Map<String, Json>, k: &str) -> Result<String, Failure> {
    Ok(checked_id(need(input, k))?)
}

fn role(input: &Map<String, Json>) -> Result<Role, Failure> {
    Role::of(need(input, "role"))
        .filter(|r| *r != Role::Owner)
        .ok_or_else(|| invalid("role must be editor or viewer"))
}

/// A method's answer.
async fn call(
    hud: &Arc<Hud>,
    caller: &Caller,
    name: &str,
    input: &Map<String, Json>,
) -> Result<Json, Failure> {
    let c = &hud.canvases;
    let me = caller.who();
    let origin = &hud.config.public_origin;
    let tabs = || async {
        let (open, current) = c.tabs(me).await;
        let open = c.tab_views(me, &open).await;
        json!({ "open": open, "current": current })
    };
    let viewed =
        |id: String| async move { Ok::<_, Failure>(json!({ "canvas": c.info(me, &id).await? })) };
    let tiled = |canvas: String, op: Op| async move {
        let tile = c.apply(me, &canvas, op, By::Person).await?;
        Ok::<_, Failure>(json!({ "tile": c.tile_view(&canvas, &tile, origin).await }))
    };
    Ok(match name {
        "getWorkspace" => {
            let mut v = tabs().await;
            let mut actor = json!({ "did": me.did });
            if let Some(h) = &me.handle {
                actor["handle"] = json!(h);
            }
            v["launchers"] = json!(hud_core::view::launchers(me.did, me.handle));
            v["me"] = actor;
            v["signInAgain"] = json!(hud.behind(&caller.account).await);
            if let Some(theme) = hud.themes.get(me.did) {
                v["theme"] = json!(theme);
            }
            v["themes"] = json!(hud_core::theme::all());
            v
        }
        "listCanvases" => {
            let limit = input
                .get("limit")
                .and_then(Json::as_u64)
                .map_or(PAGE, |l| (l as usize).clamp(1, PAGE_MAX));
            let after = text(input, "cursor").unwrap_or_default();
            let all = c.list(me).await;
            let rest: Vec<(String, Json)> = all
                .into_iter()
                .filter(|(k, _)| k.as_str() > after)
                .collect();
            let more = rest.len() > limit;
            let page: Vec<(String, Json)> = rest.into_iter().take(limit).collect();
            let mut v =
                json!({ "canvases": page.iter().map(|(_, c)| c.clone()).collect::<Vec<_>>() });
            if let (true, Some((k, _))) = (more, page.last()) {
                v["cursor"] = json!(k);
            }
            v
        }
        "getCanvas" => c.canvas(me, &id(input, "canvas")?, origin).await?,
        "createCanvas" => {
            let name = checked_name(need(input, "name"))?;
            viewed(c.create(me, &name, By::Person).await?.id).await?
        }
        "updateCanvas" => {
            let name = checked_name(need(input, "name"))?;
            viewed(c.rename(me, &id(input, "canvas")?, &name).await?.id).await?
        }
        "deleteCanvas" => {
            c.delete(me, &id(input, "canvas")?).await?;
            json!({})
        }
        "openCanvas" => {
            let opened = c.open_canvas(me, &id(input, "canvas")?).await?;
            let mut v = tabs().await;
            v["canvas"] = c.info(me, &opened.id).await?;
            v
        }
        "closeCanvas" => {
            c.close_canvas(me, &id(input, "canvas")?).await?;
            tabs().await
        }
        "setTabOrder" => {
            let order = input["tabs"]
                .as_array()
                .into_iter()
                .flatten()
                .map(|t| Ok(checked_id(t["canvas"].as_str().unwrap_or_default())?))
                .collect::<Result<Vec<String>, Failure>>()?;
            c.set_tabs(me, &order).await?;
            tabs().await
        }
        "setTheme" => {
            let theme = match (text(input, "key"), text(input, "uri")) {
                (Some(_), Some(_)) => {
                    return Err(invalid("Name a theme by its key or its uri, not both"));
                }
                (Some(key), None) => Some(
                    hud_core::theme::builtin(key)
                        .ok_or_else(|| invalid(format!("HUD has no theme {key}")))?
                        .clone(),
                ),
                (None, Some(uri)) => Some(hud.person_theme(uri).await?),
                (None, None) => None,
            };
            // HUD's by key alone, drawn as it is then; a person's copied.
            let kept = theme.as_ref().map(|t| match t.get("key") {
                Some(key) => json!({ "key": key }),
                None => t.clone(),
            });
            hud.themes.set(me.did, kept.as_ref())?;
            c.workspace_changed(me.did);
            match theme {
                Some(t) => json!({ "theme": t }),
                None => json!({}),
            }
        }
        "listThemes" => {
            let limit = input
                .get("limit")
                .and_then(Json::as_u64)
                .map_or(25, |l| l.clamp(1, 50)) as u32;
            let (themes, cursor) = hud
                .list_themes(text(input, "actor"), limit, text(input, "cursor"))
                .await?;
            let mut v = json!({ "themes": themes });
            if let Some(c) = cursor {
                v["cursor"] = json!(c);
            }
            v
        }
        "createTheme" => {
            let theme = hud
                .create_theme(
                    &caller.account,
                    need(input, "name"),
                    need(input, "colorScheme"),
                    &input["palette"],
                )
                .await?;
            json!({ "theme": theme })
        }
        "deleteTheme" => {
            hud.delete_theme(&caller.account, need(input, "uri"))
                .await?;
            json!({})
        }
        "checkTheme" => {
            let palette = hud_core::theme::palette(&input["palette"])?;
            json!({ "problems": hud_core::theme::problems(&palette) })
        }
        "getLogs" => {
            let lines = hud.read_logs(&caller.account, input).await?;
            let lines: Vec<Json> = lines
                .into_iter()
                .map(|line| json!({ "line": line }))
                .collect();
            json!({ "lines": lines })
        }
        "getAccountData" => {
            let kept = hud.kept(&caller.account).await;
            let canvases: Vec<Json> = kept
                .canvases
                .owned
                .iter()
                .map(
                    |(id, name, members)| json!({ "canvas": id, "name": name, "members": members }),
                )
                .collect();
            json!({
                "did": me.did,
                "canvases": canvases,
                "shared": kept.canvases.shared,
                "invitations": kept.canvases.invited,
                "themes": kept.themes,
                "chosenTheme": kept.chosen,
            })
        }
        "deleteAccountData" => {
            if need(input, "did") != me.did {
                return Err(fail(
                    StatusCode::FORBIDDEN,
                    "Forbidden",
                    "Only your own data is deleted: name your own DID",
                ));
            }
            // The page, or HUD's own app: never another MCP client the
            // person connected, which could wipe everything with one call.
            let ours = match &caller.proof {
                Proof::Cookie(_) => true,
                Proof::Token(_) => {
                    let auth = hud.auth().expect("a token's caller is signed in");
                    auth.from_app(&caller.account).await
                }
            };
            if !ours {
                return Err(fail(
                    StatusCode::FORBIDDEN,
                    "Forbidden",
                    "Your data is deleted from HUD's own pages or app alone",
                ));
            }
            let deleted = hud
                .delete_account_data(&caller.account)
                .await
                .map_err(|why| fail(StatusCode::BAD_GATEWAY, "UpstreamFailure", why))?;
            json!({ "deleted": deleted })
        }
        "declineInvite" => {
            let canvas = id(input, "canvas")?;
            let info = c
                .info_of(&canvas)
                .await
                .filter(|i| i.member(me.did).is_some())
                .ok_or_else(|| Refused::NoCanvas(canvas.clone()))?;
            if info.member(me.did).is_some_and(|m| m.joined) {
                return Err(invalid(format!(
                    "You are in \"{}\" already: leave it instead",
                    info.name
                )));
            }
            c.remove(me, &canvas, me.did).await?;
            json!({})
        }
        "inviteMember" => {
            let (canvas, role) = (id(input, "canvas")?, role(input)?);
            let actor = need(input, "actor");
            let found = hud
                .resolve_actor(actor)
                .await
                .map_err(|why| invalid(format!("{actor} cannot be invited: {why}")))?;
            let info = c
                .invite(me, &canvas, &found.did, found.handle.as_deref(), role)
                .await?;
            viewed(info.id).await?
        }
        "setMemberRole" => {
            let (canvas, role) = (id(input, "canvas")?, role(input)?);
            viewed(c.set_role(me, &canvas, need(input, "did"), role).await?.id).await?
        }
        "removeMember" => {
            let (canvas, did) = (id(input, "canvas")?, need(input, "did"));
            if did == me.did {
                return Err(invalid("To leave a canvas yourself, leaveCanvas"));
            }
            viewed(c.remove(me, &canvas, did).await?.id).await?
        }
        "leaveCanvas" => {
            c.remove(me, &id(input, "canvas")?, me.did).await?;
            json!({})
        }
        "addTile" => {
            let checked_tile = |k: &str| text(input, k).map(checked_id).transpose();
            let canvas = id(input, "canvas")?;
            let tool = checked_tool(need(input, "tool"))?;
            let arguments = checked_arguments(input.get("arguments"))?;
            let title = text(input, "title").map(checked_title).transpose()?;
            let (from, after, stack) = (
                checked_tile("from")?,
                checked_tile("after")?,
                checked_tile("stack")?,
            );
            let width = text(input, "width").map(checked_width).transpose()?;
            let arguments = hud.canonical_call(&tool, &arguments).await;
            // The same call on the canvas already: that tile, none added.
            match hud.same_tile(me, &canvas, &tool, &arguments).await? {
                Some(tile) => json!({
                    "tile": c.tile_view(&canvas, &tile, origin).await,
                    "existing": true,
                }),
                None => {
                    // With none given, a feed's tile is titled by its name.
                    let title = match title {
                        Some(t) => Some(t),
                        None => hud.feed_title(&tool, &arguments).await,
                    };
                    let op = Op::Add {
                        tool,
                        arguments,
                        title,
                        from,
                        after,
                        stack,
                        width,
                    };
                    tiled(canvas, op).await?
                }
            }
        }
        "removeTile" => {
            c.apply(
                me,
                &id(input, "canvas")?,
                Op::Remove {
                    id: id(input, "tile")?,
                },
                By::Person,
            )
            .await?;
            json!({})
        }
        "placeTile" => {
            let to = Beside::of(text(input, "before"), text(input, "after"))?;
            tiled(
                id(input, "canvas")?,
                Op::Place {
                    id: id(input, "tile")?,
                    to,
                },
            )
            .await?
        }
        "setTileWidth" => {
            let width = checked_width(need(input, "width"))?;
            tiled(
                id(input, "canvas")?,
                Op::Width {
                    id: id(input, "tile")?,
                    width,
                },
            )
            .await?
        }
        "stackTile" => {
            let op = Op::Stack {
                id: id(input, "tile")?,
                into: id(input, "into")?,
            };
            tiled(id(input, "canvas")?, op).await?
        }
        "unstackTile" => {
            tiled(
                id(input, "canvas")?,
                Op::Unstack {
                    id: id(input, "tile")?,
                },
            )
            .await?
        }
        "updateTile" => {
            let title = text(input, "title").map(checked_title).transpose()?;
            // Another call drawn in the same tile, as a tab chosen in it:
            // made canonical as an added tile's is.
            let call = match text(input, "tool") {
                Some(tool) => {
                    let tool = checked_tool(tool)?;
                    let arguments = checked_arguments(input.get("arguments"))?;
                    let arguments = hud.canonical_call(&tool, &arguments).await;
                    Some((tool, arguments))
                }
                None if input.contains_key("arguments") => {
                    return Err(invalid("arguments are given with their tool"));
                }
                None => None,
            };
            if title.is_none() && call.is_none() {
                return Err(invalid("Give a title, or a tool and its arguments"));
            }
            tiled(
                id(input, "canvas")?,
                Op::Update {
                    id: id(input, "tile")?,
                    title,
                    call,
                },
            )
            .await?
        }
        "callTool" => {
            let tool = need(input, "name");
            if tool.starts_with("canvas_") {
                return Err(invalid(
                    "The canvas tools are an agent's: the workspace changes the canvas through its own methods",
                ));
            }
            // The workspace's page draws with the web renderer, as current
            // as HUD; an app, with the kit it says (`kit`), else the oldest.
            let kit = match caller.proof {
                Proof::Cookie(_) => Kit::current("workspace"),
                Proof::Token(_) => Kit::said(input.get("kit")),
            };
            // One `mcp tool` line, as `/mcp` logs a tools/call, so the
            // page's and the app's calls show alike (`telemetry::tool`).
            let started = Instant::now();
            let logged = |error: Option<&str>, reason: Option<&str>| {
                hud_core::telemetry::tool(&hud_core::telemetry::Tool {
                    name: tool,
                    did: Some(caller.account.did.as_str()),
                    error,
                    reason,
                    took: started.elapsed(),
                    kit: kit.said.as_deref(),
                })
            };
            let answered = match hud
                .call_tool(tool, input.get("arguments"), Some(&caller.account))
                .await
            {
                None => return Err(invalid(format!("Unknown tool: {tool}"))),
                // The page and the app offer signing in again, the
                // session still good for what it was asked for.
                Some(Err(Refusal::SignIn)) if hud.behind(&caller.account).await => {
                    Err(hud_core::oauth::SIGN_IN_AGAIN.to_string())
                }
                Some(Err(Refusal::SignIn)) => {
                    logged(None, Some("sign-in asked"));
                    return Err(fail(
                        StatusCode::UNAUTHORIZED,
                        "AuthRequired",
                        "Your sign-in at your PDS ended: sign in again",
                    ));
                }
                Some(Err(Refusal::Error(e))) => Err(e),
                Some(Ok(mut out)) => {
                    hud_core::kit::fit(&mut out.meta, &kit);
                    Ok(out)
                }
            };
            logged(answered.as_ref().err().map(String::as_str), None);
            json!({ "result": tool_result(answered, false) })
        }
        _ => {
            return Err(fail(
                StatusCode::NOT_IMPLEMENTED,
                "MethodNotImplemented",
                format!("HUD has no method {NS}{name}"),
            ));
        }
    })
}

/// An event stream's state: the person's stream of notices, the caller it
/// is for, and what it has yet to send.
struct Listening {
    hud: Arc<Hud>,
    caller: Caller,
    watch: Watch,
    queue: VecDeque<SseEvent>,
}

/// `getWorkspaceEvents`: the person's open canvases' changes and who is on
/// them, and their workspace's changes, each a `data:` line of JSON typed
/// by its `$type`, with a `ping` comment when idle. It follows the tabs as
/// they open and close; it ends when the session does, it falls too far
/// behind, or the server stops: the page connects again and reads afresh.
async fn events(hud: Arc<Hud>, caller: Caller) -> Response {
    let watch = hud.canvases.watch(caller.who()).await;
    let listening = Listening {
        hud,
        caller,
        watch,
        queue: VecDeque::new(),
    };
    let stream = futures::stream::unfold(listening, |mut l| async move {
        loop {
            if let Some(e) = l.queue.pop_front() {
                return Some((Ok::<_, Infallible>(e), l));
            }
            tokio::select! {
                got = l.watch.notices.recv() => {
                    let notice = got.ok()?;
                    let sent = match &notice {
                        Notice::Tile { canvas, .. } | Notice::Presence { canvas, .. } => l.watch.covers(canvas),
                        Notice::Canvases { .. } => {
                            l.hud.canvases.follow(&mut l.watch).await;
                            true
                        }
                    };
                    if sent {
                        let data = l.hud.canvases.notice_json(&notice, &l.hud.config.public_origin).await;
                        l.queue.push_back(SseEvent::default().data(data.to_string()));
                    }
                }
                () = tokio::time::sleep(RECHECK) => {
                    if !l.caller.live(&l.hud) {
                        return None;
                    }
                }
            }
        }
    });
    Sse::new(stream)
        .keep_alive(KeepAlive::new().interval(PING).text("ping"))
        .into_response()
}

#[cfg(test)]
mod tests;