~ 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
1659 lines · 63.7 KB Raw History
//! The MCP endpoint, `POST /mcp`: Streamable HTTP, JSON answers (an SSE
//! event only to a client that takes nothing else), dual-era as Monolith's
//! is. A request whose `_meta` names the protocol version is served
//! statelessly as 2026-07-28, its `MCP-Protocol-Version`, `Mcp-Method` and
//! (for `tools/call` and `resources/read`) `Mcp-Name` headers held to its
//! body; an `initialize`, and the requests after it that name a legacy
//! version in `MCP-Protocol-Version`, as 2025-11-25 or 2025-06-18, with no
//! session. Either era has the same tools and the one view resource,
//! `ui://records/view/<hash of the view>` (`crate::VIEW_URI`), a new URI
//! for each build of the view; the lists change only with the server, so
//! the modern era's say they keep an hour. A request from a page of another
//! site (an `Origin` neither this machine's nor the server's public origin)
//! is refused, so a
//! site cannot reach a server on its visitor's machine. Each tool's tree
//! is fitted to the kit that draws it (`hud_core::kit`): a modern
//! request's `place.hud/kit` client capability, HUD's own view's for MCP
//! Apps' and the legacy era's, else the oldest.
//!
//! With sign-in on, a request may carry HUD's access token as `Bearer`: a
//! live session's makes its calls the account's, and its results' cache
//! scope private. Any other token is answered HTTP 401 with the
//! `invalid_token` challenge, and a tool that needs an account, called with
//! no token, with the challenge that names the resource's metadata and
//! scope: so that the host signs in (MCP's authorization spec).

use crate::VIEW_URI;
use axum::body::Body;
use axum::extract::State;
use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header};
use axum::response::{IntoResponse, Response};
use base64::Engine;
use hud_core::Hud;
use hud_core::kit::Kit;
use hud_core::oauth::Account;
use hud_core::tools::{self, Output, Refusal};
use serde_json::{Map, Value as Json, json};
use std::sync::Arc;
use std::time::Instant;

/// The modern protocol version.
const VERSION: &str = "2026-07-28";
/// The legacy versions, opened by `initialize`: the first is answered to a
/// client asking for one not served.
const LEGACY: [&str; 2] = ["2025-11-25", "2025-06-18"];
/// Every version served.
const SUPPORTED: [&str; 3] = [VERSION, LEGACY[0], LEGACY[1]];
/// What the server says of itself, to a client of either era: the
/// collections the bundled views draw, by their own descriptions, and,
/// with sign-in on (`asked`, the scope it asks for), what signing in
/// allows, and the workspace's canvas where it is served (`workspace`,
/// its origin).
fn instructions(asked: Option<&str>, workspace: Option<&str>) -> String {
    let oauth = asked.is_some();
    let base = if oauth {
        "Views of atproto data from any account on any PDS; signed in, writes and personal queries as the account."
    } else {
        "Read-only views of public atproto data from any account on any PDS."
    };
    let writes = if oauth {
        " Signed in (the host asks the person to sign in when a tool needs it), query is called as the account through its PDS, and create_record and delete_record write to its own repository (likes, reposts, any record whose lexicon resolves); views' Like and Repost buttons call them. For the person's own things, use me as the actor: \"my Bluesky timeline\" is query app.bsky.feed.getTimeline; \"my posts\" is query app.bsky.feed.getAuthorFeed with params { actor: \"me\" }; \"my profile\" is describe_repo actor me; \"my knotless\" is describe_app domain knotless.dev, actor me. \"My feeds\" is query app.bsky.feed.getFeedGenerators with params { feeds: \"saved\" } (or \"pinned\"); one of them by name is query app.bsky.feed.getFeed with params { feed: \"<its name>\" }, as \"For You\"; \"Following\" is the timeline."
    } else {
        ""
    };
    let canvas = match workspace.filter(|_| oauth) {
        Some(origin) => format!(
            " With sign-in on, HUD also keeps canvases for each person at {origin}/workspace, their own and those shared with them, each a strip of columns, left to right, one tile or a stack of up to three each: canvas_add puts any read tool's result on their current canvas (or the one canvas names) as a tile they, and those it is shared with, see live, at the strip's end, or with from right after what was opened from that tile already (e.g. canvas_add tool query arguments {{method: app.bsky.feed.getFeed, params: {{feed: \"For You\"}}}}); canvas_create makes a canvas, canvas_list lists them and a canvas's tiles in strip order, canvas_place moves a tile beside another and sets its column's width, and canvas_remove takes one off."
        ),
        None => String::new(),
    };
    let actor = if oauth {
        "An actor is a handle, a DID, or me."
    } else {
        "An actor is a handle or a DID."
    };
    format!(
        "{base} describe_repo shows an account as its profile across the apps it uses; describe_app shows an app by its domain (bsky.app for app.bsky.*): where to go in it and, with an actor, that account's things in it. get_record opens a record a bundled query view draws as that query ({}): a post as its thread. list_records and get_record draw records of any other collection with a view: one passed inline, else a bundled one ({}), else generically. query calls a service's XRPC queries, as an AppView's feeds, and draws the answer with a view the same way ({}).{writes}{canvas} To draw something your own way, read describe_collection or describe_method for its schema and the component catalog, then pass a view. {actor}",
        tools::bundled_records(),
        tools::bundled_collections(),
        tools::bundled_methods()
    )
}

/// The scope sign-in asks for; none with sign-in off.
fn scope_asked(hud: &Hud) -> Option<&str> {
    hud.oauth.as_ref().map(|a| a.scope.as_str())
}

/// The origin the workspace is served at; none where it is not
/// (`HUD_WORKSPACE=off`).
fn workspace_at(hud: &Hud) -> Option<&str> {
    let c = &hud.config;
    c.workspace.then_some(c.public_origin.as_str())
}

/// The tools `account` is offered: everyone's, and to HUD's operators
/// alone (`HUD_OPERATOR_DIDS`), `admin_logs`, which refuses anyone else.
fn tool_list(hud: &Hud, account: Option<&Account>) -> Vec<Json> {
    let workspace = hud.config.workspace;
    let mut tools = tools::definitions(scope_asked(hud), workspace, VIEW_URI);
    tools.extend(hud.operator(account).then(hud_core::logs::definition));
    tools
}

/// How long list and read results stay fresh, in milliseconds.
const TTL_MS: u64 = 3_600_000;
/// The most of a request body read.
const MAX_BODY: usize = 1024 * 1024;
/// The view's MIME type, as MCP Apps names it.
const VIEW_MIME: &str = "text/html;profile=mcp-app";

const PARSE_ERROR: i64 = -32700;
const INVALID_REQUEST: i64 = -32600;
const METHOD_NOT_FOUND: i64 = -32601;
const INVALID_PARAMS: i64 = -32602;
const RESOURCE_NOT_FOUND: i64 = -32002;
const HEADER_MISMATCH: i64 = -32020;
const UNSUPPORTED_PROTOCOL_VERSION: i64 = -32022;

/// A JSON-RPC error, with the HTTP status it is answered with; or, where
/// `sign_in`, the HTTP 401 challenge instead.
#[derive(Debug)]
struct RpcError {
    status: StatusCode,
    code: i64,
    message: String,
    data: Option<Json>,
    sign_in: bool,
}

fn rpc_err(status: StatusCode, code: i64, message: impl Into<String>) -> RpcError {
    RpcError {
        status,
        code,
        message: message.into(),
        data: None,
        sign_in: false,
    }
}

pub async fn endpoint(
    State(hud): State<Arc<Hud>>,
    method: Method,
    headers: HeaderMap,
    body: Body,
) -> Response {
    if let Some(origin) = headers.get(header::ORIGIN)
        && !allowed_origin(origin, &hud.config.public_origin)
    {
        return error_response(
            None,
            rpc_err(StatusCode::FORBIDDEN, INVALID_REQUEST, "Origin not allowed"),
            false,
        );
    }
    if method != Method::POST {
        return (StatusCode::METHOD_NOT_ALLOWED, [(header::ALLOW, "POST")]).into_response();
    }
    // A bearer token: a live session's, or the challenge.
    let token = headers.get(header::AUTHORIZATION).is_some();
    let account = match bearer(&hud, &headers) {
        Ok(a) => a,
        Err(()) => return challenge(&hud, true, ""),
    };
    let sse = wants_sse(&headers);
    let Ok(body) = axum::body::to_bytes(body, MAX_BODY).await else {
        return error_response(
            None,
            rpc_err(
                StatusCode::PAYLOAD_TOO_LARGE,
                INVALID_REQUEST,
                "The request body is too large or could not be read",
            ),
            sse,
        );
    };
    let Ok(message) = serde_json::from_slice::<Json>(&body) else {
        return error_response(
            None,
            rpc_err(StatusCode::BAD_REQUEST, PARSE_ERROR, "Parse error"),
            sse,
        );
    };
    let Json::Object(message) = message else {
        return error_response(
            None,
            rpc_err(
                StatusCode::BAD_REQUEST,
                INVALID_REQUEST,
                "Not a JSON-RPC request",
            ),
            sse,
        );
    };
    let id = message
        .get("id")
        .filter(|id| id.is_string() || id.is_i64() || id.is_u64())
        .cloned();
    let rpc_method = message.get("method").and_then(Json::as_str);
    let Some(rpc_method) = rpc_method.filter(|_| message.get("jsonrpc") == Some(&json!("2.0")))
    else {
        return error_response(
            id,
            rpc_err(
                StatusCode::BAD_REQUEST,
                INVALID_REQUEST,
                "Not a JSON-RPC request",
            ),
            sse,
        );
    };
    match (message.get("id"), id) {
        // A notification: none needs anything done.
        (None, _) => StatusCode::ACCEPTED.into_response(),
        (Some(_), None) => error_response(
            None,
            rpc_err(
                StatusCode::BAD_REQUEST,
                INVALID_REQUEST,
                "A request id must be a string or an integer",
            ),
            sse,
        ),
        (Some(_), Some(id)) => {
            let started = Instant::now();
            let params = message.get("params");
            let kit = Kit::of_params(params);
            let answer = request(&hud, &headers, rpc_method, params, account.as_ref(), &kit).await;
            match rpc_method {
                "tools/call" => called(params, account.as_ref(), &kit, &answer, started.elapsed()),
                _ => failed(rpc_method, &answer),
            }
            match answer {
                Ok(result) => {
                    let answer = json!({ "jsonrpc": "2.0", "id": id, "result": result });
                    reply(StatusCode::OK, &answer, sse)
                }
                Err(e) if e.sign_in => challenge(&hud, token, &e.message),
                Err(e) => error_response(Some(id), e, sse),
            }
        }
    }
}

/// Logs a tool call, by the tool's name, the caller and the kit drawing
/// it, as it ended: its error where it failed, never its arguments or
/// result (`telemetry::tool`).
fn called(
    params: Option<&Json>,
    account: Option<&Account>,
    kit: &Kit,
    answer: &Result<Json, RpcError>,
    took: std::time::Duration,
) {
    let name = params.and_then(|p| p.get("name")).and_then(Json::as_str);
    let (error, reason) = match answer {
        Ok(result) => {
            let failed = result["isError"] == json!(true);
            let text = result["content"][0]["text"].as_str();
            (text.filter(|_| failed), None)
        }
        Err(e) if e.sign_in => (None, Some("sign-in asked")),
        Err(e) => (Some(e.message.as_str()), None),
    };
    hud_core::telemetry::tool(&hud_core::telemetry::Tool {
        name: name.unwrap_or_default(),
        did: account.map(|a| a.did.as_str()),
        error,
        reason,
        took,
        kit: kit.said.as_deref(),
    });
}

/// Logs a request other than a tool call that was answered an error
/// (`telemetry::rpc_failed`).
fn failed(method: &str, answer: &Result<Json, RpcError>) {
    if let Err(e) = answer {
        hud_core::telemetry::rpc_failed(method, &e.message);
    }
}

/// The account a request's bearer token is for: none with sign-in off or
/// no `Authorization` header; refused for any token that is not a live
/// session's current access token.
pub(crate) fn bearer(hud: &Hud, headers: &HeaderMap) -> Result<Option<Account>, ()> {
    let (Some(auth), Some(value)) = (&hud.oauth, headers.get(header::AUTHORIZATION)) else {
        return Ok(None);
    };
    let value = value.to_str().map_err(|_| ())?;
    let (scheme, token) = value.split_once(' ').ok_or(())?;
    if !scheme.eq_ignore_ascii_case("bearer") {
        return Err(());
    }
    auth.account(token.trim()).map(Some).ok_or(())
}

/// HTTP 401 with a `WWW-Authenticate: Bearer` challenge naming the
/// resource's metadata: `invalid_token` for a token that no longer works,
/// else the scope to sign in with, and `why` as its description: what the
/// tool asks of the person (`tools::sign_in_words`).
fn challenge(hud: &Hud, invalid: bool, why: &str) -> Response {
    let metadata = format!(
        "{}/.well-known/oauth-protected-resource/mcp",
        hud.config.public_origin
    );
    let (www, why) = if invalid {
        (
            format!("Bearer error=\"invalid_token\", resource_metadata=\"{metadata}\""),
            "The token is not one HUD gave, or it expired or was revoked: sign in again",
        )
    } else {
        (
            format!(
                "Bearer resource_metadata=\"{metadata}\", scope=\"{}\"",
                hud_core::oauth::SCOPE
            ),
            why,
        )
    };
    (
        StatusCode::UNAUTHORIZED,
        [
            (header::WWW_AUTHENTICATE, www),
            (header::CONTENT_TYPE, "application/json".to_string()),
        ],
        json!({ "error": "invalid_token", "error_description": why }).to_string(),
    )
        .into_response()
}

/// Whether a request's `Origin` may reach the endpoint: this machine's,
/// which a page on another site never is, or the server's own.
fn allowed_origin(origin: &HeaderValue, public_origin: &str) -> bool {
    let Ok(o) = origin.to_str() else { return false };
    if o.eq_ignore_ascii_case(public_origin) {
        return true;
    }
    let Some(rest) = o
        .strip_prefix("http://")
        .or_else(|| o.strip_prefix("https://"))
    else {
        return false;
    };
    let host = match rest.strip_prefix('[') {
        Some(v6) => v6.split_once(']').map_or("", |(h, _)| h),
        None => rest.split(':').next().unwrap_or(""),
    };
    matches!(host, "localhost" | "127.0.0.1" | "::1")
}

/// Whether the client takes only an SSE stream, not JSON.
fn wants_sse(headers: &HeaderMap) -> bool {
    let accept = headers
        .get(header::ACCEPT)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    accept.contains("text/event-stream")
        && !accept.contains("application/json")
        && !accept.contains("*/*")
}

fn reply(status: StatusCode, message: &Json, sse: bool) -> Response {
    if sse {
        let event = format!("event: message\ndata: {message}\n\n");
        (
            status,
            [
                (header::CONTENT_TYPE, "text/event-stream"),
                (header::CACHE_CONTROL, "no-cache"),
            ],
            event,
        )
            .into_response()
    } else {
        (
            status,
            [(header::CONTENT_TYPE, "application/json")],
            message.to_string(),
        )
            .into_response()
    }
}

fn error_response(id: Option<Json>, e: RpcError, sse: bool) -> Response {
    let mut error = json!({ "code": e.code, "message": e.message });
    if let Some(data) = e.data {
        error["data"] = data;
    }
    let mut message = json!({ "jsonrpc": "2.0", "error": error });
    if let Some(id) = id {
        message["id"] = id;
    }
    reply(e.status, &message, sse)
}

/// A request header's value, or a `HeaderMismatch` naming it if it is missing or not text.
fn required_header<'a>(headers: &'a HeaderMap, name: &str) -> Result<&'a str, RpcError> {
    match headers.get(name).map(HeaderValue::to_str) {
        Some(Ok(v)) => Ok(v),
        Some(Err(_)) => Err(rpc_err(
            StatusCode::BAD_REQUEST,
            HEADER_MISMATCH,
            format!("The {name} header is not valid text"),
        )),
        None => Err(rpc_err(
            StatusCode::BAD_REQUEST,
            HEADER_MISMATCH,
            format!("The {name} header is missing"),
        )),
    }
}

/// A header value as sent, decoded if it is in the `=?base64?…?=` form.
fn decoded(value: &str) -> Option<String> {
    match value
        .strip_prefix("=?base64?")
        .and_then(|v| v.strip_suffix("?="))
    {
        Some(b64) => {
            String::from_utf8(base64::engine::general_purpose::STANDARD.decode(b64).ok()?).ok()
        }
        None => Some(value.to_string()),
    }
}

fn mismatch(name: &str, header: &str, body: &str) -> RpcError {
    rpc_err(
        StatusCode::BAD_REQUEST,
        HEADER_MISMATCH,
        format!(
            "Header mismatch: {name} header value '{header}' does not match body value '{body}'"
        ),
    )
}

/// Answer a request in the era it opens: an `initialize`, or a legacy
/// `MCP-Protocol-Version` with no `_meta` version, is legacy; anything else
/// is held to the modern rules. A tool's tree is fitted to `kit`.
async fn request(
    hud: &Hud,
    headers: &HeaderMap,
    method: &str,
    params: Option<&Json>,
    account: Option<&Account>,
    kit: &Kit,
) -> Result<Json, RpcError> {
    if method == "initialize" {
        return initialize(hud, params);
    }
    let meta_version = params
        .and_then(|p| p.get("_meta"))
        .and_then(|m| m.get("io.modelcontextprotocol/protocolVersion"));
    let header = headers
        .get("mcp-protocol-version")
        .and_then(|v| v.to_str().ok());
    if meta_version.is_none() && header.is_none_or(|v| LEGACY.contains(&v)) {
        return legacy(hud, method, params, account, kit).await;
    }
    modern(hud, headers, method, params, account, kit).await
}

/// The legacy handshake: the version asked for if served, else the latest
/// legacy one; no session.
fn initialize(hud: &Hud, params: Option<&Json>) -> Result<Json, RpcError> {
    let Some(asked) = params
        .and_then(|p| p.get("protocolVersion"))
        .and_then(Json::as_str)
    else {
        return Err(rpc_err(
            StatusCode::OK,
            INVALID_PARAMS,
            "params.protocolVersion is required",
        ));
    };
    let version = LEGACY
        .iter()
        .find(|v| **v == asked)
        .copied()
        .unwrap_or(LEGACY[0]);
    Ok(json!({
        "protocolVersion": version,
        "capabilities": capabilities(),
        "serverInfo": server_info(),
        "instructions": instructions(scope_asked(hud), workspace_at(hud)),
    }))
}

/// A request after `initialize`, in a legacy revision's shape: the same
/// methods and answers as the modern era's, without its fields, and
/// `ping`. Errors are HTTP 200.
async fn legacy(
    hud: &Hud,
    method: &str,
    params: Option<&Json>,
    account: Option<&Account>,
    kit: &Kit,
) -> Result<Json, RpcError> {
    let params = match params {
        None | Some(Json::Null) => &Map::new(),
        Some(Json::Object(p)) => p,
        Some(_) => {
            return Err(rpc_err(
                StatusCode::OK,
                INVALID_PARAMS,
                "params must be an object",
            ));
        }
    };
    match method {
        "ping" => Ok(json!({})),
        "tools/list" => {
            no_cursor(params)?;
            Ok(json!({ "tools": tool_list(hud, account) }))
        }
        "resources/list" => {
            no_cursor(params)?;
            Ok(json!({ "resources": [view_resource(hud)] }))
        }
        "resources/templates/list" => {
            no_cursor(params)?;
            Ok(json!({ "resourceTemplates": [] }))
        }
        "resources/read" => read_resource(hud, params),
        "tools/call" => call_tool(hud, params, false, account, kit).await,
        _ => Err(rpc_err(
            StatusCode::OK,
            METHOD_NOT_FOUND,
            format!("Method not found: {method}"),
        )),
    }
}

/// Check a modern request's headers and `_meta`, then answer it with its result.
async fn modern(
    hud: &Hud,
    headers: &HeaderMap,
    method: &str,
    params: Option<&Json>,
    account: Option<&Account>,
    kit: &Kit,
) -> Result<Json, RpcError> {
    let version = required_header(headers, "mcp-protocol-version").map_err(|mut e| {
        e.message = format!(
            "{}; this server supports protocol versions {}",
            e.message,
            SUPPORTED.join(", ")
        );
        e
    })?;
    if version != VERSION {
        return Err(RpcError {
            data: Some(json!({ "supported": SUPPORTED, "requested": version })),
            ..rpc_err(
                StatusCode::BAD_REQUEST,
                UNSUPPORTED_PROTOCOL_VERSION,
                "Unsupported protocol version",
            )
        });
    }
    let header_method = required_header(headers, "mcp-method")?;
    if header_method != method {
        return Err(mismatch("Mcp-Method", header_method, method));
    }
    if !matches!(
        method,
        "server/discover"
            | "tools/list"
            | "tools/call"
            | "resources/list"
            | "resources/templates/list"
            | "resources/read"
    ) {
        return Err(rpc_err(
            StatusCode::NOT_FOUND,
            METHOD_NOT_FOUND,
            format!("Method not found: {method}"),
        ));
    }
    let invalid = |m: &str| rpc_err(StatusCode::BAD_REQUEST, INVALID_PARAMS, m);
    let Some(Json::Object(params)) = params else {
        return Err(invalid("params with _meta are required"));
    };
    let Some(Json::Object(meta)) = params.get("_meta") else {
        return Err(invalid("params._meta is required"));
    };
    let Some(meta_version) = meta
        .get("io.modelcontextprotocol/protocolVersion")
        .and_then(Json::as_str)
    else {
        return Err(invalid(
            "_meta must name io.modelcontextprotocol/protocolVersion",
        ));
    };
    if !meta
        .get("io.modelcontextprotocol/clientCapabilities")
        .is_some_and(Json::is_object)
    {
        return Err(invalid(
            "_meta must have io.modelcontextprotocol/clientCapabilities",
        ));
    }
    if meta_version != version {
        return Err(mismatch("MCP-Protocol-Version", version, meta_version));
    }
    // `Mcp-Name` names what `tools/call` calls and `resources/read` reads.
    let named = match method {
        "tools/call" => Some("name"),
        "resources/read" => Some("uri"),
        _ => None,
    };
    if let Some(key) = named {
        let header_name = required_header(headers, "mcp-name")?;
        let Some(header_name) = decoded(header_name) else {
            return Err(rpc_err(
                StatusCode::BAD_REQUEST,
                HEADER_MISMATCH,
                "The Mcp-Name header is not valid base64",
            ));
        };
        let Some(body_name) = params.get(key).and_then(Json::as_str) else {
            return Err(rpc_err(
                StatusCode::OK,
                INVALID_PARAMS,
                format!("params.{key} is required"),
            ));
        };
        if header_name != body_name {
            return Err(mismatch("Mcp-Name", &header_name, body_name));
        }
    }
    // Cache fields, where a result has them: private to the account when
    // the request is one's.
    let scope = if account.is_some() {
        "private"
    } else {
        "public"
    };
    let cached = |mut result: Json| {
        result["resultType"] = json!("complete");
        result["_meta"] = server_meta();
        result["ttlMs"] = json!(TTL_MS);
        result["cacheScope"] = json!(scope);
        result
    };
    match method {
        "server/discover" => Ok(cached(json!({
            "supportedVersions": SUPPORTED,
            "capabilities": capabilities(),
            "serverInfo": server_info(),
            "instructions": instructions(scope_asked(hud), workspace_at(hud)),
        }))),
        "tools/list" => {
            no_cursor(params)?;
            Ok(cached(json!({ "tools": tool_list(hud, account) })))
        }
        "resources/list" => {
            no_cursor(params)?;
            Ok(cached(json!({ "resources": [view_resource(hud)] })))
        }
        "resources/templates/list" => {
            no_cursor(params)?;
            Ok(cached(json!({ "resourceTemplates": [] })))
        }
        "resources/read" => read_resource(hud, params).map(cached),
        _ => call_tool(hud, params, true, account, kit).await,
    }
}

/// A list's request may name no cursor: every list is one page.
fn no_cursor(params: &Map<String, Json>) -> Result<(), RpcError> {
    match params.get("cursor") {
        Some(c) if !c.is_null() => Err(rpc_err(StatusCode::OK, INVALID_PARAMS, "Invalid cursor")),
        _ => Ok(()),
    }
}

fn capabilities() -> Json {
    json!({ "tools": {}, "resources": {} })
}

/// The server's name and version, as either era names it.
fn server_info() -> Json {
    json!({ "name": "hud", "title": "HUD", "version": env!("CARGO_PKG_VERSION") })
}

fn server_meta() -> Json {
    json!({ "io.modelcontextprotocol/serverInfo": server_info() })
}

/// The view's UI metadata: it calls only the server's own origin, fetches
/// only a `Map`'s tiles besides (`MAP_TILES`), and loads
/// media from there (the blob proxy), from the origins the bundled views
/// trust (Bluesky's video service and CDN among them, for posts' videos'
/// HLS), and from the image CDN public records' images come from: for
/// every view, a model's too, as they serve nothing but media.
fn view_meta(hud: &Hud) -> Json {
    let origin = &hud.config.public_origin;
    let mut resources = hud_core::view::csp_origins(origin);
    if let Some(cdn) = hud.config.image_cdn_origin()
        && !resources.contains(&cdn)
    {
        resources.push(cdn);
    }
    json!({ "ui": {
        "csp": {
            "connectDomains": [origin, hud_core::catalog::MAP_TILES],
            "resourceDomains": resources,
        },
        "prefersBorder": true,
    } })
}

/// The one resource, the view, as `resources/list` lists it.
fn view_resource(hud: &Hud) -> Json {
    json!({
        "uri": VIEW_URI,
        "name": "records-view",
        "title": "atproto record view",
        "description": "Galleries and records from atproto accounts",
        "mimeType": VIEW_MIME,
        "_meta": view_meta(hud),
    })
}

/// `resources/read`: the view, or `Resource not found`.
fn read_resource(hud: &Hud, params: &Map<String, Json>) -> Result<Json, RpcError> {
    let Some(uri) = params.get("uri").and_then(Json::as_str) else {
        return Err(rpc_err(
            StatusCode::OK,
            INVALID_PARAMS,
            "params.uri is required",
        ));
    };
    if uri != VIEW_URI {
        return Err(RpcError {
            data: Some(json!({ "uri": uri })),
            ..rpc_err(StatusCode::OK, RESOURCE_NOT_FOUND, "Resource not found")
        });
    }
    Ok(json!({ "contents": [{
        "uri": VIEW_URI,
        "mimeType": VIEW_MIME,
        "text": crate::VIEW_HTML,
        "_meta": view_meta(hud),
    }] }))
}

/// `tools/call`: the tool's answer, its tree fitted to the kit drawing it
/// (`kit::fit`), or its error as a result; an unknown tool is `Invalid
/// params`, and one that needs the caller to sign in the endpoint's
/// challenge.
async fn call_tool(
    hud: &Hud,
    params: &Map<String, Json>,
    modern: bool,
    account: Option<&Account>,
    kit: &Kit,
) -> Result<Json, RpcError> {
    let Some(name) = params.get("name").and_then(Json::as_str) else {
        return Err(rpc_err(
            StatusCode::OK,
            INVALID_PARAMS,
            "params.name must be a tool's name",
        ));
    };
    let Some(answer) = hud.call_tool(name, params.get("arguments"), account).await else {
        return Err(rpc_err(
            StatusCode::OK,
            INVALID_PARAMS,
            format!("Unknown tool: {name}"),
        ));
    };
    let answer = match answer {
        Ok(mut out) => {
            hud_core::kit::fit(&mut out.meta, kit);
            Ok(out)
        }
        Err(Refusal::Error(e)) => Err(e),
        Err(Refusal::SignIn) => {
            return Err(RpcError {
                sign_in: true,
                ..rpc_err(
                    StatusCode::UNAUTHORIZED,
                    INVALID_REQUEST,
                    hud_core::tools::sign_in_words(name, params.get("arguments")),
                )
            });
        }
    };
    Ok(tool_result(answer, modern))
}

/// A tool's answer as a `CallToolResult` of either era.
pub(crate) fn tool_result(answer: Result<Output, String>, modern: bool) -> Json {
    let mut result = match answer {
        Ok(out) => json!({
            "content": [{ "type": "text", "text": out.text }],
            "structuredContent": out.structured,
            "isError": false,
            "_meta": out.meta,
        }),
        Err(message) => json!({
            "content": [{ "type": "text", "text": message }],
            "isError": true,
        }),
    };
    if modern {
        result["resultType"] = json!("complete");
        let meta = result
            .as_object_mut()
            .expect("a result is an object")
            .entry("_meta")
            .or_insert_with(|| json!({}));
        meta["io.modelcontextprotocol/serverInfo"] = server_info();
    }
    result
}

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

    /// The one account the servers here name as their operator.
    const OPERATOR: &str = "did:plc:operator";

    fn hud() -> Arc<Hud> {
        hud_with(false)
    }

    /// A server, with sign-in on or off; on, its key and sessions in a
    /// directory of its own.
    fn hud_with(oauth: bool) -> Arc<Hud> {
        hud_of(oauth, "https://images.example/img")
    }

    /// As `hud_with`, its image CDN `image_cdn`.
    fn hud_of(oauth: bool, image_cdn: &str) -> Arc<Hud> {
        let data_dir =
            std::env::temp_dir().join(format!("hud-mcp-tests-{}", atproto::jose::random(6)));
        Hud::new(Config {
            port: 8787,
            bind: "::".parse().unwrap(),
            public_origin: "https://hud.example".into(),
            cache_dir: std::env::temp_dir().join("hud-mcp-tests"),
            data_dir,
            oauth,
            oauth_scope: hud_core::scope::asked(hud_core::view::views(), true, false),
            oauth_include: None,
            workspace: true,
            spaces: false,
            plc_url: "https://plc.directory".into(),
            handle_resolver: None,
            allow_private: false,
            blob_cache_bytes: 0,
            cache_memory_bytes: 1 << 24,
            backlinks: hud_core::backlinks::Backlinks::None,
            favicons: None,
            image_cdn: Some(image_cdn.into()),
            relay: None,
            sign_up_pds: hud_core::config::SIGN_UP_PDS.into(),
            client: Default::default(),
            // One operator, whose server keeps its lines with sign-in on.
            operators: vec![OPERATOR.into()],
            logs: oauth,
            logs_keep: hud_core::logs::KEEP,
        })
        .unwrap()
    }

    /// `headers` (name, value) as a request's.
    fn header_map(headers: &[(&str, &str)]) -> HeaderMap {
        let mut h = HeaderMap::new();
        for (k, v) in headers {
            h.insert(
                header::HeaderName::from_bytes(k.as_bytes()).unwrap(),
                HeaderValue::from_str(v).unwrap(),
            );
        }
        h
    }

    /// A request of `method` to `hud` with `headers` and `body`: the
    /// answer's status, headers and bytes.
    async fn raw(
        hud: Arc<Hud>,
        method: Method,
        headers: HeaderMap,
        body: impl Into<Body>,
    ) -> (StatusCode, HeaderMap, Vec<u8>) {
        let r = endpoint(State(hud), method, headers, body.into()).await;
        let status = r.status();
        let headers = r.headers().clone();
        let bytes = axum::body::to_bytes(r.into_body(), usize::MAX)
            .await
            .unwrap();
        (status, headers, bytes.to_vec())
    }

    /// POST a message to `hud` with `headers` (name, value): the answer's
    /// status, headers and body.
    async fn send(
        hud: Arc<Hud>,
        headers: &[(&str, &str)],
        body: Json,
    ) -> (StatusCode, HeaderMap, Json) {
        let (status, headers, bytes) =
            raw(hud, Method::POST, header_map(headers), body.to_string()).await;
        let body = if bytes.is_empty() {
            Json::Null
        } else {
            serde_json::from_slice(&bytes).unwrap()
        };
        (status, headers, body)
    }

    /// POST a message with `headers` (name, value), and the answer's status and body.
    async fn post(headers: &[(&str, &str)], body: Json) -> (StatusCode, Json) {
        let (status, _, body) = send(hud(), headers, body).await;
        (status, body)
    }

    #[tokio::test]
    async fn sign_in_challenges() {
        let hud = hud_with(true);
        let metadata = "https://hud.example/.well-known/oauth-protected-resource/mcp";
        let call = |name: &str, arguments: Json| {
            json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call",
                    "params": { "name": name, "arguments": arguments } })
        };
        let list = json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" });
        // Sign-in on: the seven read tools, the three that write, the
        // canvas's five, then the view's four.
        let (_, _, body) = send(hud.clone(), &[], list.clone()).await;
        let tools = body["result"]["tools"].as_array().unwrap();
        assert_eq!(tools.len(), 19);
        assert_eq!(tools[7]["name"], "create_record");
        assert_eq!(tools[8]["name"], "apply_writes");
        let names: Vec<&str> = tools[10..15]
            .iter()
            .filter_map(|t| t["name"].as_str())
            .collect();
        assert_eq!(
            names,
            [
                "canvas_list",
                "canvas_add",
                "canvas_place",
                "canvas_remove",
                "canvas_create"
            ]
        );
        assert_eq!(tools[15]["name"], "send_interactions");
        assert_eq!(tools[15]["_meta"]["ui"]["visibility"], json!(["app"]));
        // The instructions name the workspace.
        let init = json!({ "jsonrpc": "2.0", "id": 1, "method": "initialize",
                           "params": { "protocolVersion": LEGACY[0] } });
        let (_, _, body) = send(hud.clone(), &[], init).await;
        assert!(
            body["result"]["instructions"]
                .as_str()
                .unwrap()
                .contains("canvases for each person at https://hud.example/workspace")
        );
        // Interactions and the canvas with no token: the challenge.
        let seen = call(
            "send_interactions",
            json!({ "feed": "at://did:plc:x/app.bsky.feed.generator/f",
                    "interactions": [{ "item": "at://did:plc:x/app.bsky.feed.post/1",
                                       "event": "app.bsky.feed.defs#interactionSeen" }] }),
        );
        let (status, _, _) = send(hud.clone(), &[], seen).await;
        assert_eq!(status, StatusCode::UNAUTHORIZED);
        for (name, arguments) in [
            ("canvas_list", json!({})),
            (
                "canvas_add",
                json!({ "tool": "describe_repo", "arguments": { "actor": "alice.test" } }),
            ),
            (
                "canvas_place",
                json!({ "id": "0123456789ab", "after": "0123456789ac" }),
            ),
            ("canvas_remove", json!({ "id": "0123456789ab" })),
            ("canvas_create", json!({ "name": "Coast trip" })),
        ] {
            let (status, h, _) = send(hud.clone(), &[], call(name, arguments)).await;
            assert_eq!(status, StatusCode::UNAUTHORIZED, "{name}");
            assert_eq!(
                h[header::WWW_AUTHENTICATE],
                format!("Bearer resource_metadata=\"{metadata}\", scope=\"hud\""),
                "{name}"
            );
        }
        // A write with no token: the challenge, naming the scope, so the
        // host signs in; not a tool error.
        let like = call(
            "create_record",
            json!({ "collection": "app.bsky.feed.like", "record": {} }),
        );
        let (status, h, body) = send(hud.clone(), &[], like.clone()).await;
        assert_eq!(status, StatusCode::UNAUTHORIZED);
        assert_eq!(
            h[header::WWW_AUTHENTICATE],
            format!("Bearer resource_metadata=\"{metadata}\", scope=\"hud\"")
        );
        assert_eq!(body["error"], "invalid_token");
        // Saying what the tool asks of the person.
        assert_eq!(body["error_description"], hud_core::tools::SIGN_IN);
        let mut modern = modern_body(
            "tools/call",
            json!({ "name": "delete_record", "arguments": { "uri": "at://did:plc:x/a.b.c/1" } }),
        );
        modern["id"] = json!(2);
        let (status, _, _) = send(
            hud.clone(),
            &[
                ("mcp-protocol-version", VERSION),
                ("mcp-method", "tools/call"),
                ("mcp-name", "delete_record"),
            ],
            modern,
        )
        .await;
        assert_eq!(status, StatusCode::UNAUTHORIZED);
        // A token HUD did not give, or not as Bearer: invalid_token, on
        // any request.
        for auth in ["Bearer not-a-token", "DPoP x", "Bearer"] {
            let (status, h, _) = send(hud.clone(), &[("authorization", auth)], list.clone()).await;
            assert_eq!(status, StatusCode::UNAUTHORIZED, "{auth}");
            assert_eq!(
                h[header::WWW_AUTHENTICATE],
                format!("Bearer error=\"invalid_token\", resource_metadata=\"{metadata}\""),
                "{auth}"
            );
        }
        // Tools that need no account answer as before with no token.
        let (status, _, body) = send(
            hud.clone(),
            &[],
            call("get_record", json!({ "uri": "not a uri" })),
        )
        .await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body["result"]["isError"], true);
        assert!(body["result"]["_meta"].get("viewer").is_none());
        // Sign-in off: no writes, and a token is not looked at.
        let off = hud_with(false);
        let (status, _, body) = send(off.clone(), &[], like).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body["error"]["code"], INVALID_PARAMS);
        let (status, _, body) = send(off, &[("authorization", "Bearer not-a-token")], list).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body["result"]["tools"].as_array().unwrap().len(), 7);
    }

    fn modern_body(method: &str, mut params: Json) -> Json {
        params["_meta"] = json!({
            "io.modelcontextprotocol/protocolVersion": VERSION,
            "io.modelcontextprotocol/clientCapabilities": {},
        });
        json!({ "jsonrpc": "2.0", "id": 1, "method": method, "params": params })
    }

    async fn modern_call(method: &str, name: Option<&str>, params: Json) -> (StatusCode, Json) {
        let mut headers = vec![("mcp-protocol-version", VERSION), ("mcp-method", method)];
        if let Some(n) = name {
            headers.push(("mcp-name", n));
        }
        post(&headers, modern_body(method, params)).await
    }

    #[tokio::test]
    async fn legacy_initialize() {
        let (status, body) = post(
            &[],
            json!({ "jsonrpc": "2.0", "id": 1, "method": "initialize",
                    "params": { "protocolVersion": "2025-06-18", "capabilities": {},
                                "clientInfo": { "name": "t", "version": "1" } } }),
        )
        .await;
        assert_eq!(status, StatusCode::OK);
        let r = &body["result"];
        assert_eq!(r["protocolVersion"], "2025-06-18");
        assert_eq!(r["capabilities"], json!({ "tools": {}, "resources": {} }));
        let (_, body) = post(
            &[],
            json!({ "jsonrpc": "2.0", "id": 1, "method": "initialize",
                    "params": { "protocolVersion": "2099-01-01" } }),
        )
        .await;
        assert_eq!(body["result"]["protocolVersion"], LEGACY[0]);
        // After it, the legacy era's lists, without the modern fields.
        let (_, body) = post(
            &[("mcp-protocol-version", "2025-11-25")],
            json!({ "jsonrpc": "2.0", "id": 2, "method": "tools/list" }),
        )
        .await;
        assert_eq!(body["result"]["tools"].as_array().unwrap().len(), 7);
        assert!(body["result"].get("ttlMs").is_none());
    }

    #[tokio::test]
    async fn modern_header_mismatch() {
        let (status, body) = post(
            &[
                ("mcp-protocol-version", VERSION),
                ("mcp-method", "tools/call"),
            ],
            modern_body("tools/list", json!({})),
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(body["error"]["code"], HEADER_MISMATCH);
        let (status, body) = modern_call(
            "resources/read",
            Some("ui://other"),
            json!({ "uri": VIEW_URI }),
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(body["error"]["code"], HEADER_MISMATCH);
        let (_, body) = modern_call("resources/read", None, json!({ "uri": VIEW_URI })).await;
        assert_eq!(body["error"]["code"], HEADER_MISMATCH);
        let (status, body) = post(
            &[
                ("mcp-protocol-version", "2024-11-05"),
                ("mcp-method", "tools/list"),
            ],
            modern_body("tools/list", json!({})),
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(body["error"]["code"], UNSUPPORTED_PROTOCOL_VERSION);
    }

    #[tokio::test]
    async fn cache_fields() {
        for method in ["server/discover", "tools/list", "resources/list"] {
            let (status, body) = modern_call(method, None, json!({})).await;
            assert_eq!(status, StatusCode::OK, "{method}");
            assert_eq!(body["result"]["ttlMs"], TTL_MS, "{method}");
            assert_eq!(body["result"]["cacheScope"], "public", "{method}");
            assert_eq!(body["result"]["resultType"], "complete", "{method}");
        }
        let (_, body) =
            modern_call("resources/read", Some(VIEW_URI), json!({ "uri": VIEW_URI })).await;
        let r = &body["result"];
        assert_eq!(
            (r["ttlMs"].clone(), r["cacheScope"].clone()),
            (json!(TTL_MS), json!("public"))
        );
        let content = &r["contents"][0];
        assert_eq!(content["mimeType"], VIEW_MIME);
        assert_eq!(content["text"], crate::VIEW_HTML);
        let csp = &content["_meta"]["ui"]["csp"];
        assert_eq!(
            csp["connectDomains"],
            json!(["https://hud.example", hud_core::catalog::MAP_TILES])
        );
        let domains = csp["resourceDomains"].as_array().unwrap();
        let mut bundled = hud_core::view::csp_origins("https://hud.example");
        bundled.push("https://images.example".into());
        assert_eq!(csp["resourceDomains"], json!(bundled));
        assert!(domains.contains(&json!("https://hud.example")));
        for v in hud_core::blobs::VIDEO_ORIGINS {
            assert!(domains.contains(&json!(v)), "{v}");
        }
        assert!(domains.contains(&json!("https://audio.plyr.fm")));
        // The image CDN (HUD_IMAGE_CDN's origin), once.
        let cdn = json!("https://images.example");
        assert_eq!(domains.iter().filter(|d| **d == cdn).count(), 1);
        // Bluesky's video service and CDN, once each.
        for v in hud_core::blobs::VIDEO_ORIGINS {
            assert_eq!(domains.iter().filter(|d| **d == v).count(), 1, "{v}");
        }
        let (_, body) = modern_call("resources/list", None, json!({})).await;
        assert_eq!(body["result"]["resources"][0]["uri"], VIEW_URI);
    }

    #[tokio::test]
    async fn unknown_resource_and_tool() {
        let (_, body) = modern_call(
            "resources/read",
            Some("ui://nothing"),
            json!({ "uri": "ui://nothing" }),
        )
        .await;
        assert_eq!(body["error"]["code"], RESOURCE_NOT_FOUND);
        assert_eq!(body["error"]["message"], "Resource not found");
        let (_, body) = post(
            &[],
            json!({ "jsonrpc": "2.0", "id": 1, "method": "resources/read",
                    "params": { "uri": "ui://nothing" } }),
        )
        .await;
        assert_eq!(body["error"]["code"], RESOURCE_NOT_FOUND);
        let (status, body) = modern_call(
            "tools/call",
            Some("nope"),
            json!({ "name": "nope", "arguments": {} }),
        )
        .await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body["error"]["code"], INVALID_PARAMS);
        let (_, body) = post(
            &[],
            json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call",
                    "params": { "name": "nope" } }),
        )
        .await;
        assert_eq!(body["error"]["code"], INVALID_PARAMS);
    }

    /// A bad argument is the tool's own error, in either era, never JSON-RPC's.
    #[tokio::test]
    async fn bad_input_is_a_tool_error() {
        let (_, body) = modern_call(
            "tools/call",
            Some("get_record"),
            json!({ "name": "get_record", "arguments": { "uri": "not a uri" } }),
        )
        .await;
        let r = &body["result"];
        assert_eq!(r["isError"], true);
        assert_eq!(r["resultType"], "complete");
        assert!(
            r["content"][0]["text"]
                .as_str()
                .unwrap()
                .starts_with("Not a record's at-uri")
        );
        let (_, body) = post(
            &[],
            json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call",
                    "params": { "name": "list_records", "arguments": { "actor": "x", "collection": "nsid" } } }),
        )
        .await;
        assert_eq!(body["result"]["isError"], true);
        assert!(body["result"].get("resultType").is_none());
    }

    #[tokio::test]
    async fn origins() {
        let list = json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" });
        for ok in [
            "http://localhost:5173",
            "http://127.0.0.1",
            "https://[::1]:8080",
            "https://hud.example",
        ] {
            let (status, _) = post(&[("origin", ok)], list.clone()).await;
            assert_eq!(status, StatusCode::OK, "{ok}");
        }
        for bad in [
            "https://evil.example",
            "http://localhost.evil.example",
            "null",
        ] {
            let (status, _) = post(&[("origin", bad)], list.clone()).await;
            assert_eq!(status, StatusCode::FORBIDDEN, "{bad}");
        }
    }

    /// The instructions name the workspace's canvases where it is served
    /// alone; signed out, never.
    #[tokio::test]
    async fn instructions_name_canvases_where_served() {
        let at = Some("https://hud.example");
        let canvases = "canvases for each person at https://hud.example/workspace";
        assert!(instructions(Some("atproto"), at).contains(canvases));
        assert!(!instructions(Some("atproto"), None).contains("canvas"));
        assert!(!instructions(None, at).contains("canvas"));
        let mut config = hud_of(true, "https://cdn.example").config.clone();
        config.workspace = false;
        assert_eq!(workspace_at(&Hud::new(config).unwrap()), None);
    }

    #[test]
    fn header_values() {
        assert_eq!(decoded("get_record").as_deref(), Some("get_record"));
        assert_eq!(
            decoded("=?base64?SGVsbG8sIOS4lueVjA==?=").as_deref(),
            Some("Hello, 世界")
        );
        assert_eq!(decoded("=?base64?!!?="), None);
    }

    #[tokio::test]
    async fn what_is_not_a_json_rpc_request() {
        let hud = hud();
        // POST alone.
        let (status, h, _) = raw(hud.clone(), Method::GET, HeaderMap::new(), "").await;
        assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
        assert_eq!(h[header::ALLOW], "POST");
        // A body past the most read, and one that is not JSON.
        let code =
            |bytes: &[u8]| serde_json::from_slice::<Json>(bytes).unwrap()["error"]["code"].clone();
        let (status, _, body) = raw(
            hud.clone(),
            Method::POST,
            HeaderMap::new(),
            vec![b' '; MAX_BODY + 1],
        )
        .await;
        assert_eq!(
            (status, code(&body)),
            (StatusCode::PAYLOAD_TOO_LARGE, json!(INVALID_REQUEST))
        );
        let (status, _, body) = raw(hud.clone(), Method::POST, HeaderMap::new(), "{").await;
        assert_eq!(
            (status, code(&body)),
            (StatusCode::BAD_REQUEST, json!(PARSE_ERROR))
        );
        // Not an object, not JSON-RPC 2.0 (its id answered still), and an
        // id neither a string nor an integer.
        for (message, id) in [
            (json!([1]), None),
            (json!({ "id": 7, "method": "tools/list" }), Some(json!(7))),
            (
                json!({ "jsonrpc": "2.0", "id": 1.5, "method": "tools/list" }),
                None,
            ),
        ] {
            let (status, body) = post(&[], message.clone()).await;
            assert_eq!(status, StatusCode::BAD_REQUEST, "{message}");
            assert_eq!(body["error"]["code"], INVALID_REQUEST, "{message}");
            assert_eq!(body.get("id").cloned(), id, "{message}");
        }
        // A notification: accepted, and nothing answered.
        let (status, body) = post(
            &[],
            json!({ "jsonrpc": "2.0", "method": "notifications/initialized" }),
        )
        .await;
        assert_eq!((status, body), (StatusCode::ACCEPTED, Json::Null));
    }

    #[tokio::test]
    async fn an_event_stream_to_a_client_that_takes_nothing_else() {
        let ping = json!({ "jsonrpc": "2.0", "id": 1, "method": "ping" });
        let only = header_map(&[("accept", "text/event-stream")]);
        let (status, h, bytes) = raw(hud(), Method::POST, only, ping.to_string()).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(h[header::CONTENT_TYPE], "text/event-stream");
        let answer = json!({ "jsonrpc": "2.0", "id": 1, "result": {} });
        assert_eq!(
            String::from_utf8(bytes).unwrap(),
            format!("event: message\ndata: {answer}\n\n")
        );
        // One that takes JSON too, or anything, is answered JSON.
        for accept in [
            "text/event-stream, application/json",
            "text/event-stream, */*",
        ] {
            let (_, h, body) = send(hud(), &[("accept", accept)], ping.clone()).await;
            assert_eq!(h[header::CONTENT_TYPE], "application/json", "{accept}");
            assert_eq!(body, answer, "{accept}");
        }
    }

    /// POST a message through the whole router, as a client sends it,
    /// with `headers` (name, value): the answer's headers and its bytes as
    /// sent.
    async fn routed(headers: &[(&str, &str)], body: Json) -> (HeaderMap, Vec<u8>) {
        use tower::ServiceExt;
        let mut request = axum::http::Request::post("/mcp")
            .body(Body::from(body.to_string()))
            .unwrap();
        *request.headers_mut() = header_map(headers);
        let r = crate::router(hud(), None).oneshot(request).await.unwrap();
        let headers = r.headers().clone();
        let bytes = axum::body::to_bytes(r.into_body(), usize::MAX)
            .await
            .unwrap();
        (headers, bytes.to_vec())
    }

    /// `bytes` read back as their `Content-Encoding` says.
    fn read_back(headers: &HeaderMap, bytes: &[u8]) -> Vec<u8> {
        use std::io::Read;
        let encoding = headers.get(header::CONTENT_ENCODING);
        let mut out = Vec::new();
        match encoding.and_then(|v| v.to_str().ok()) {
            Some("gzip") => flate2::read::GzDecoder::new(bytes).read_to_end(&mut out),
            Some("br") => brotli::Decompressor::new(bytes, 4096).read_to_end(&mut out),
            _ => return bytes.to_vec(),
        }
        .unwrap();
        out
    }

    /// An answer compressed as the client takes it, gzip or Brotli, and
    /// the same JSON read back; as it is where it takes neither of them;
    /// never an event stream or an answer under a kilobyte.
    #[tokio::test]
    async fn answers_compressed_as_the_client_takes_them() {
        let list = json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" });
        let (h, plain) = routed(&[], list.clone()).await;
        assert!(h.get(header::CONTENT_ENCODING).is_none());
        assert!(plain.len() > 1024, "{}", plain.len());
        for (takes, encoding) in [
            ("gzip", Some("gzip")),
            ("br", Some("br")),
            ("gzip;q=0.5, br", Some("br")),
            ("identity", None),
            ("zstd, deflate", None),
        ] {
            let (h, sent) = routed(&[("accept-encoding", takes)], list.clone()).await;
            let got = h.get(header::CONTENT_ENCODING);
            assert_eq!(got.map(|v| v.to_str().unwrap()), encoding, "{takes}");
            assert_eq!(h[header::CONTENT_TYPE], "application/json", "{takes}");
            if encoding.is_some() {
                assert!(sent.len() < plain.len() / 3, "{takes}: {}", sent.len());
                assert_eq!(h[header::VARY], "accept-encoding", "{takes}");
            }
            assert_eq!(read_back(&h, &sent), plain, "{takes}");
        }
        // The same answer as an event stream: as it is.
        let stream = [
            ("accept", "text/event-stream"),
            ("accept-encoding", "gzip, br"),
        ];
        let (h, sent) = routed(&stream, list).await;
        assert_eq!(h[header::CONTENT_TYPE], "text/event-stream");
        assert!(h.get(header::CONTENT_ENCODING).is_none());
        assert!(sent.starts_with(b"event: message\ndata: {"));
        assert!(sent.len() > plain.len());
        // An answer under a kilobyte: as it is.
        let ping = json!({ "jsonrpc": "2.0", "id": 1, "method": "ping" });
        let (h, sent) = routed(&[("accept-encoding", "gzip, br")], ping).await;
        assert!(h.get(header::CONTENT_ENCODING).is_none());
        assert_eq!(
            serde_json::from_slice::<Json>(&sent).unwrap(),
            json!({ "jsonrpc": "2.0", "id": 1, "result": {} })
        );
    }

    #[tokio::test]
    async fn legacy_requests() {
        let call = |method: &str, params: Json| json!({ "jsonrpc": "2.0", "id": 1, "method": method, "params": params });
        let (status, body) = post(&[], call("ping", Json::Null)).await;
        assert_eq!((status, &body["result"]), (StatusCode::OK, &json!({})));
        let (_, body) = post(&[], call("resources/list", json!({}))).await;
        assert_eq!(body["result"]["resources"][0]["uri"], VIEW_URI);
        assert!(body["result"].get("ttlMs").is_none());
        let (_, body) = post(&[], call("resources/templates/list", json!({}))).await;
        assert_eq!(body["result"], json!({ "resourceTemplates": [] }));
        // Each refused as HTTP 200: an initialize naming no version, params
        // not an object, a cursor (every list is one page), a read naming
        // nothing, a call naming no tool, and a method the era has not.
        for (method, params, code) in [
            ("initialize", json!({}), INVALID_PARAMS),
            ("tools/list", json!([1]), INVALID_PARAMS),
            ("tools/list", json!({ "cursor": "2" }), INVALID_PARAMS),
            ("resources/read", json!({}), INVALID_PARAMS),
            ("tools/call", json!({ "arguments": {} }), INVALID_PARAMS),
            ("server/discover", json!({}), METHOD_NOT_FOUND),
        ] {
            let (status, body) = post(&[], call(method, params)).await;
            assert_eq!(status, StatusCode::OK, "{method}");
            assert_eq!(body["error"]["code"], code, "{method}");
        }
    }

    #[tokio::test]
    async fn modern_requests_held_to_their_headers_and_meta() {
        let supported = "this server supports protocol versions 2026-07-28, 2025-11-25, 2025-06-18";
        let error = |body: &Json| {
            (
                body["error"]["code"].as_i64().unwrap(),
                body["error"]["message"].as_str().unwrap().to_string(),
            )
        };
        // _meta naming the version, with no header naming it, or one that
        // is not text.
        let (status, body) = post(&[], modern_body("tools/list", json!({}))).await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(
            error(&body),
            (
                HEADER_MISMATCH,
                format!("The mcp-protocol-version header is missing; {supported}")
            )
        );
        let mut h = header_map(&[("mcp-method", "tools/list")]);
        h.insert(
            "mcp-protocol-version",
            HeaderValue::from_bytes(b"\xff").unwrap(),
        );
        let message = modern_body("tools/list", json!({})).to_string();
        let (status, _, bytes) = raw(hud(), Method::POST, h, message).await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(
            error(&serde_json::from_slice(&bytes).unwrap()),
            (
                HEADER_MISMATCH,
                format!("The mcp-protocol-version header is not valid text; {supported}")
            )
        );
        // A method the modern era has not.
        let headers = |m: &'static str| [("mcp-protocol-version", VERSION), ("mcp-method", m)];
        let (status, body) = post(&headers("ping"), modern_body("ping", json!({}))).await;
        assert_eq!(
            (status, error(&body).0),
            (StatusCode::NOT_FOUND, METHOD_NOT_FOUND)
        );
        // What _meta must be, and say.
        let list = |params: Option<Json>| {
            let mut m = json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" });
            if let Some(p) = params {
                m["params"] = p;
            }
            m
        };
        let caps = "io.modelcontextprotocol/clientCapabilities";
        let version = "io.modelcontextprotocol/protocolVersion";
        for (message, why) in [
            (list(None), "params with _meta are required"),
            (list(Some(json!({}))), "params._meta is required"),
            (
                list(Some(json!({ "_meta": { caps: {} } }))),
                "_meta must name io.modelcontextprotocol/protocolVersion",
            ),
            (
                list(Some(json!({ "_meta": { version: VERSION } }))),
                "_meta must have io.modelcontextprotocol/clientCapabilities",
            ),
        ] {
            let (status, body) = post(&headers("tools/list"), message).await;
            assert_eq!(status, StatusCode::BAD_REQUEST, "{why}");
            assert_eq!(error(&body), (INVALID_PARAMS, why.to_string()));
        }
        // _meta's version, not the header's.
        let other = list(Some(json!({ "_meta": { version: LEGACY[0], caps: {} } })));
        let (status, body) = post(&headers("tools/list"), other).await;
        assert_eq!(
            (status, error(&body).0),
            (StatusCode::BAD_REQUEST, HEADER_MISMATCH)
        );
        // Mcp-Name not base64 as it says it is; a call naming no tool.
        let (status, body) = modern_call(
            "tools/call",
            Some("=?base64?!!?="),
            json!({ "name": "get_record" }),
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(
            error(&body),
            (
                HEADER_MISMATCH,
                "The Mcp-Name header is not valid base64".into()
            )
        );
        let (status, body) = modern_call("tools/call", Some("get_record"), json!({})).await;
        assert_eq!(
            (status, error(&body)),
            (
                StatusCode::OK,
                (INVALID_PARAMS, "params.name is required".into())
            )
        );
        // The templates, none, as cacheable as the other lists.
        let (_, body) = modern_call("resources/templates/list", None, json!({})).await;
        let r = &body["result"];
        assert_eq!(
            (&r["resourceTemplates"], &r["ttlMs"]),
            (&json!([]), &json!(TTL_MS))
        );
    }

    #[tokio::test]
    async fn a_signed_in_answer_is_private() {
        let hud = hud_with(true);
        let token =
            hud.auth()
                .unwrap()
                .signed_in_offline("did:plc:alice", Some("alice.test"), false);
        let bearer = format!("Bearer {token}");
        let (status, _, body) = send(
            hud.clone(),
            &[
                ("mcp-protocol-version", VERSION),
                ("mcp-method", "tools/list"),
                ("authorization", &bearer),
            ],
            modern_body("tools/list", json!({})),
        )
        .await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body["result"]["cacheScope"], "private");
    }

    #[tokio::test]
    async fn an_image_cdn_on_the_servers_own_origin() {
        let hud = hud_of(false, "https://hud.example/img");
        let list = json!({ "jsonrpc": "2.0", "id": 1, "method": "resources/list" });
        let (_, _, body) = send(hud, &[], list).await;
        let domains = &body["result"]["resources"][0]["_meta"]["ui"]["csp"]["resourceDomains"];
        assert_eq!(
            domains,
            &json!(hud_core::view::csp_origins("https://hud.example"))
        );
    }

    /// `admin_logs`: listed for HUD's operators alone, refusing anyone
    /// else; for an operator, the lines kept, as asked.
    #[tokio::test]
    async fn the_operators_logs() {
        let hud = hud_with(true);
        let auth = hud.auth().unwrap();
        let bearer = |did: &str| {
            let token = auth.signed_in_offline(did, Some("someone.test"), false);
            format!("Bearer {token}")
        };
        let (operator, alice) = (bearer(OPERATOR), bearer("did:plc:alice"));
        let list = json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" });
        let names = |body: &Json| -> Vec<String> {
            let tools = body["result"]["tools"].as_array().unwrap().iter();
            tools
                .filter_map(|t| t["name"].as_str().map(str::to_string))
                .collect()
        };
        let (_, _, body) = send(hud.clone(), &[("authorization", &operator)], list.clone()).await;
        assert_eq!(names(&body).last().unwrap(), "admin_logs");
        let (_, _, body) = send(hud.clone(), &[("authorization", &alice)], list).await;
        assert!(!names(&body).contains(&"admin_logs".to_string()));
        let call = |args: Json| {
            json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call",
                    "params": { "name": "admin_logs", "arguments": args } })
        };
        let said = |body: &Json| body["result"]["content"][0]["text"].clone();
        // No one signed in: the challenge. Another account: a refusal.
        let (status, _, _) = send(hud.clone(), &[], call(json!({ "level": "info" }))).await;
        assert_eq!(status, StatusCode::UNAUTHORIZED);
        let as_alice = [("authorization", alice.as_str())];
        let (_, _, body) = send(hud.clone(), &as_alice, call(json!({ "level": "info" }))).await;
        assert_eq!(body["result"]["isError"], true);
        assert_eq!(said(&body), "Only HUD's operators read its logs");
        // Nothing asked, or what it does not take: refused.
        let as_operator = [("authorization", operator.as_str())];
        for (args, why) in [
            (json!({}), "Ask for a trace, a message, a level or minMs"),
            (json!({ "who": 1 }), "Unknown argument: who"),
        ] {
            let (_, _, body) = send(hud.clone(), &as_operator, call(args)).await;
            assert_eq!(said(&body), why);
        }
        // The lines kept, as asked.
        let logs = hud.logs.as_ref().unwrap();
        logs.keep(br#"{"level":"WARN","message":"outgoing","trace_id":"t1","duration_ms":2000}"#);
        let (_, _, body) = send(hud.clone(), &as_operator, call(json!({ "trace": "t1" }))).await;
        assert_eq!(body["result"]["isError"], false, "{body}");
        let lines = &body["result"]["structuredContent"]["lines"];
        assert_eq!(lines[0]["message"], "outgoing");
        assert_eq!(said(&body), "Lines logged: 1.");
    }
}