~ 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
130 lines · 5.1 KB Raw History
//! HUD's HTTP surface: `POST /mcp`, the MCP endpoint (`mcp`); `GET
//! /blob/{did}/{cid}`, the proxy the view's audio, video and private images
//! are loaded through, and public images when the CDN fails (`blob`); `GET
//! /_health`, answering `ok`; apps' icons, `GET /icon/{domain}` (`icon`);
//! the terms, privacy policy and guidelines, `GET /terms`, `/privacy` and
//! `/guidelines` (`policies`); HUD's icon, `/favicon.svg`, and the
//! playground, `/playground` (`playground`); HUD's methods,
//! `/xrpc/place.hud.*` (`xrpc`), the workspace's among them with sign-in
//! on alone; and, with sign-in on, `/oauth/*` and `/.well-known/oauth-*`
//! (`oauth`) and the workspace's page, `/workspace` (`workspace`), where
//! `/` goes. With the operator's web app (`HUD_WEB`), `/`, the icons and
//! every request HUD doesn't answer itself are the app's (`web`). Each
//! request is logged and counted, in its trace (`telemetry`), whose
//! listener of its own answers `/metrics` and `PUT /log`; and each answer
//! that is text, of a kilobyte or more, is compressed, gzip or Brotli as
//! the client takes (`compressed`).

#![forbid(unsafe_code)]

mod blob;
mod icon;
mod mcp;
mod oauth;
mod playground;
mod policies;
pub mod telemetry;
mod web;
mod workspace;
mod xrpc;

use axum::Router;
use axum::http::{Extensions, HeaderMap, StatusCode, Version, header};
use axum::routing::{any, get};
use hud_core::Hud;
use hud_core::net::Web;
use std::net::SocketAddr;
use std::sync::Arc;
use tower_http::compression::CompressionLayer;
use tower_http::compression::predicate::{Predicate, SizeAbove};

include!(concat!(env!("OUT_DIR"), "/view.rs"));

/// The server's routes, over its state, each request logged and counted,
/// each answer worth it compressed; with the web app (`web`), its pages
/// in place of `/` and HUD's icon, and of every request no route takes.
/// The workspace's page and the playground are there where the workspace
/// is served alone (`Config::workspace`).
pub fn router(hud: Arc<Hud>, web: Option<Web>) -> Router {
    let mut routes = Router::new()
        .route("/mcp", any(mcp::endpoint))
        .route("/blob/{did}/{cid}", get(blob::blob))
        .route("/_health", get(|| async { "ok" }))
        .route("/icon/{domain}", get(icon::icon))
        .merge(policies::routes())
        .merge(xrpc::routes());
    let workspace = hud.config.workspace;
    if workspace {
        routes = routes.merge(playground::routes());
    }
    if hud.oauth.is_some() {
        routes = routes.merge(oauth::routes());
    }
    if hud.oauth.is_some() && workspace {
        routes = routes.merge(workspace::routes());
    }
    let routes = match web {
        Some(web) => web::pages(routes, web, &hud.config.public_origin),
        None => routes
            .route("/", get(workspace::home))
            .route("/favicon.svg", get(workspace::favicon)),
    };
    telemetry::observed(routes.with_state(hud)).layer(compressed())
}

/// The smallest answer compressed: below it, what compression saves is
/// less than its header and the time it takes.
const COMPRESSED_FROM: u16 = 1024;

/// Answers compressed as the client's `Accept-Encoding` takes them, gzip
/// or Brotli (at 4, quick enough for each answer afresh), none where it
/// takes neither: no proxy in front of HUD encodes them. Only text, `/mcp`'s
/// and the methods' JSON, the pages and the web app's scripts and styles:
/// never an event stream, nor a blob or an icon, already compressed, nor
/// what the web app compressed itself. A body that comes in parts, as a
/// page the web app streams, is compressed part by part, each sent on as
/// it's compressed. Logged at their size before it (`telemetry`).
fn compressed() -> CompressionLayer<impl Predicate> {
    CompressionLayer::new()
        .no_deflate()
        .no_zstd()
        .compress_when(SizeAbove::new(COMPRESSED_FROM).and(read_whole))
}

/// Whether an answer is text a client reads whole: JSON, HTML, SVG, or
/// the web app's scripts and styles.
fn read_whole(_: StatusCode, _: Version, headers: &HeaderMap, _: &Extensions) -> bool {
    let kind = headers.get(header::CONTENT_TYPE);
    let kind = kind.and_then(|v| v.to_str().ok()).unwrap_or_default();
    [
        "application/json",
        "text/html",
        "image/svg+xml",
        "text/javascript",
        "text/css",
    ]
    .iter()
    .any(|t| kind.starts_with(t))
}

/// Serve the routes, with the web app's pages if there is one, on
/// `listener` until `stop`, then let what is in flight finish. Each
/// request knows the address it came from, which the web app is told. The
/// workspace's event streams end then too (`Canvases::close`): open, they
/// would keep the server from ever stopping, refusing every new connection
/// meanwhile.
pub async fn serve(
    listener: tokio::net::TcpListener,
    hud: Arc<Hud>,
    web: Option<Web>,
    stop: impl Future<Output = ()> + Send + 'static,
) -> std::io::Result<()> {
    let streams = hud.clone();
    let routes = router(hud, web).into_make_service_with_connect_info::<SocketAddr>();
    axum::serve(listener, routes)
        .with_graceful_shutdown(async move {
            stop.await;
            streams.canvases.close();
        })
        .await
}