~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
1076 lines · 37.0 KB Raw History
//! The MCP endpoint, `POST /mcp`: Streamable HTTP, dual-era
//! (`spec/COMMANDS.md`, "The MCP endpoint"). A request with `_meta`'s
//! protocol version is served statelessly as 2026-07-28, with
//! `server/discover`, `tools/list` and `tools/call`; an `initialize`, and the
//! requests after it that name a legacy version in `MCP-Protocol-Version`,
//! as 2025-11-25 or 2025-06-18, statelessly too, with no session. Each
//! method with a JSON answer, or none, is a tool, called through the same
//! handling as XRPC; after them, the admin's reads, `admin_logs` and
//! `admin_stats`, answered as `/xrpc/_logs` and `/xrpc/_stats` (`ops::read`),
//! and then the account's own routes, `oauth_sessions`,
//! `oauth_revoke_session`, `oauth_devices` and `oauth_revoke_device`, and
//! `passkey_list`, `passkey_add` and `passkey_remove`, answered as
//! `/xrpc/_oauthSessions` and the others (`oauth::account`).

use crate::oauth::account::{self, Route as Own};
use crate::oauth::mcp::Token as McpToken;
use crate::sessions::Bearer;
use crate::{Auth, Call, Resp, Shared, XrpcError, answer, authorization, limits, ops, scopes};
use axum::body::Body;
use axum::extract::{Extension, State};
use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header};
use axum::response::{IntoResponse, Response};
use base64::Engine;
use pds_lexicon::{Kind, Method as Lexicon};
use serde_json::{Map, Value as Json, json};
use std::sync::OnceLock;

/// 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, as `server/discover` and `UnsupportedProtocolVersionError` name them.
const SUPPORTED: [&str; 3] = [VERSION, LEGACY[0], LEGACY[1]];
/// What the server says of itself, to a client of either era.
const INSTRUCTIONS: &str = "An atproto PDS holding any number of accounts. Each tool is an XRPC method of the server, with its arguments and answer; a `repo` or `did` left out, with a token, is the token's account's DID.";

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

/// A JSON-RPC error, with the HTTP status it is answered with; or, with a
/// `challenge`, an HTTP `401` or `403` with that `WWW-Authenticate: Bearer`
/// challenge and the OAuth error its body names, and `message` its
/// `error_description` (`spec/OAUTH-MCP.md`).
struct RpcError {
    status: StatusCode,
    code: i64,
    message: String,
    data: Option<Json>,
    challenge: Option<(String, &'static str)>,
}

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

/// The `401` that has a client sign in, or sign in again: `error`, if any,
/// names what is wrong with the token it sent (`spec/OAUTH-MCP.md`,
/// "Tokens at the MCP endpoint").
fn challenge(st: &Shared, error: Option<&str>, description: &str) -> RpcError {
    let metadata = crate::oauth::mcp::resource_metadata(st);
    let challenge = match error {
        Some(e) => format!("Bearer error=\"{e}\", resource_metadata=\"{metadata}\""),
        None => {
            format!("Bearer resource_metadata=\"{metadata}\", scope=\"atproto transition:generic\"")
        }
    };
    RpcError {
        challenge: Some((challenge, "invalid_token")),
        ..rpc_err(StatusCode::UNAUTHORIZED, INVALID_REQUEST, description)
    }
}

/// The `403` that has a client ask for more (MCP's step-up), for an error a
/// token of scope `granted` was refused with, if it is a `ScopeMissingError`:
/// the scope it names, then `also`, the others the call needs that the token
/// lacks, after the token's own, so that one sign-in grants all of it
/// (`spec/OAUTH-MCP.md`, "Tokens at the MCP endpoint").
fn step_up(st: &Shared, granted: &[String], also: &[String], e: &XrpcError) -> Option<RpcError> {
    if e.status != 403 || e.name != "ScopeMissingError" {
        return None;
    }
    let missing = e
        .message
        .strip_prefix("Missing required scope \"")?
        .strip_suffix('"')?;
    let mut scope: Vec<&str> = granted.iter().map(String::as_str).collect();
    for s in std::iter::once(missing).chain(also.iter().map(String::as_str)) {
        if !scope.contains(&s) {
            scope.push(s);
        }
    }
    let metadata = crate::oauth::mcp::resource_metadata(st);
    let description = e.message.replace('"', "'");
    Some(RpcError {
        challenge: Some((
            format!(
                "Bearer error=\"insufficient_scope\", scope=\"{}\", resource_metadata=\"{metadata}\", error_description=\"{description}\"",
                scope.join(" ")
            ),
            "insufficient_scope",
        )),
        ..rpc_err(StatusCode::FORBIDDEN, INVALID_REQUEST, e.message.clone())
    })
}

pub async fn endpoint(
    State(st): State<Shared>,
    method: Method,
    headers: HeaderMap,
    peer: Option<Extension<limits::Peer>>,
    body: Body,
) -> Response {
    if let Some(origin) = headers.get(header::ORIGIN)
        && !local_origin(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();
    }
    let sse = wants_sse(&headers);
    let body = match limits::read_body(body, limits::MAX_MCP_BODY).await {
        Some(b) if b.len() <= limits::MAX_MCP_BODY => b,
        Some(_) => {
            return error_response(
                None,
                rpc_err(
                    StatusCode::PAYLOAD_TOO_LARGE,
                    INVALID_REQUEST,
                    "Request body too large",
                ),
                sse,
            );
        }
        None => {
            return error_response(
                None,
                rpc_err(
                    StatusCode::BAD_REQUEST,
                    PARSE_ERROR,
                    "The body could not be read",
                ),
                sse,
            );
        }
    };
    let client = limits::client(
        &st.config.trusted_proxies,
        &headers,
        peer.map(|Extension(p)| p.0),
    );
    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 params = message.get("params");
            let answer = match request(&st, &headers, rpc_method, params, client).await {
                Ok(result) => json!({ "jsonrpc": "2.0", "id": id, "result": result }),
                Err(e) => return error_response(Some(id), e, sse),
            };
            reply(StatusCode::OK, &answer, sse)
        }
    }
}

/// Whether an `Origin` is this machine's, which a page on another site never is.
fn local_origin(origin: &HeaderValue) -> bool {
    let Ok(o) = origin.to_str() else { return false };
    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"),
            ],
            [("x-accel-buffering", "no")],
            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 {
    if let Some((c, error)) = e.challenge {
        let body = json!({ "error": error, "error_description": e.message });
        let mut r = (
            e.status,
            [(header::CONTENT_TYPE, "application/json")],
            body.to_string(),
        )
            .into_response();
        if let Ok(v) = HeaderValue::from_str(&c) {
            r.headers_mut().insert(header::WWW_AUTHENTICATE, v);
        }
        return r;
    }
    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.
async fn request(
    st: &Shared,
    headers: &HeaderMap,
    method: &str,
    params: Option<&Json>,
    client: String,
) -> Result<Json, RpcError> {
    if method == "initialize" {
        return initialize(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_some_and(|v| LEGACY.contains(&v)) {
        return legacy(st, headers, method, params, client).await;
    }
    modern(st, headers, method, params, client).await
}

/// The legacy handshake (`mcp/legacy/2025-11-25/basic/lifecycle.md`): the
/// version asked for if served, else the latest legacy one; no session.
fn initialize(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": { "tools": {} },
        "serverInfo": server_info(),
        "instructions": INSTRUCTIONS,
    }))
}

/// A request after `initialize`, in a legacy revision's shape: `ping`,
/// `tools/list` and `tools/call`, the same tools and answers as the modern
/// era's, without its fields; anything else not found. Errors are HTTP 200.
async fn legacy(
    st: &Shared,
    headers: &HeaderMap,
    method: &str,
    params: Option<&Json>,
    client: String,
) -> 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" => match params.get("cursor") {
            Some(c) if !c.is_null() => {
                Err(rpc_err(StatusCode::OK, INVALID_PARAMS, "Invalid cursor"))
            }
            _ => Ok(json!({ "tools": tools() })),
        },
        "tools/call" => {
            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 (content, is_error) = call_tool(
                st,
                name,
                params.get("arguments"),
                authorization(headers),
                client,
            )
            .await?;
            Ok(json!({
                "content": [{ "type": "text", "text": content.to_string() }],
                "structuredContent": content,
                "isError": is_error,
            }))
        }
        _ => 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(
    st: &Shared,
    headers: &HeaderMap,
    method: &str,
    params: Option<&Json>,
    client: String,
) -> 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 {
            status: StatusCode::BAD_REQUEST,
            code: UNSUPPORTED_PROTOCOL_VERSION,
            message: "Unsupported protocol version".into(),
            data: Some(json!({ "supported": SUPPORTED, "requested": version })),
            challenge: None,
        });
    }
    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") {
        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));
    }
    match method {
        "server/discover" => Ok(discover()),
        "tools/list" => match params.get("cursor") {
            Some(c) if !c.is_null() => {
                Err(rpc_err(StatusCode::OK, INVALID_PARAMS, "Invalid cursor"))
            }
            _ => Ok(list_tools()),
        },
        _ => {
            let name = params.get("name").and_then(Json::as_str);
            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(name) = name else {
                return Err(rpc_err(
                    StatusCode::OK,
                    INVALID_PARAMS,
                    "params.name must be a tool's name",
                ));
            };
            if header_name != name {
                return Err(mismatch("Mcp-Name", &header_name, name));
            }
            let (content, is_error) = call_tool(
                st,
                name,
                params.get("arguments"),
                authorization(headers),
                client,
            )
            .await?;
            Ok(json!({
                "resultType": "complete",
                "content": [{ "type": "text", "text": content.to_string() }],
                "structuredContent": content,
                "isError": is_error,
                "_meta": server_meta(),
            }))
        }
    }
}

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

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

fn discover() -> Json {
    json!({
        "resultType": "complete",
        "supportedVersions": SUPPORTED,
        "capabilities": { "tools": {} },
        "instructions": INSTRUCTIONS,
        "_meta": server_meta(),
        "ttlMs": 0,
        "cacheScope": "public",
    })
}

/// Every tool, the same in either era: each method's, then the admin's
/// reads', then the account's own routes'.
fn tools() -> Vec<Json> {
    pds_lexicon::methods()
        .iter()
        .filter_map(|m| {
            let name = m.tool()?;
            let mut tool =
                json!({ "name": name, "title": m.title(), "inputSchema": m.input_schema() });
            if let Some(d) = &m.description {
                tool["description"] = json!(d);
            }
            if let Some(a) = m.annotations() {
                tool["annotations"] = a;
            }
            Some(tool)
        })
        .chain(ops::Read::tools())
        .chain(Own::tools())
        .collect()
}

fn list_tools() -> Json {
    json!({ "resultType": "complete", "tools": tools(), "_meta": server_meta(), "ttlMs": 0, "cacheScope": "public" })
}

/// A query parameter's text, as XRPC takes it.
fn param_text(v: &Json) -> String {
    match v {
        Json::String(s) => s.clone(),
        other => other.to_string(),
    }
}

/// A query's parameters, from a tool's arguments: an array as the parameter
/// repeated, a null left out.
fn query_params(args: &Map<String, Json>) -> Vec<(String, String)> {
    let mut params = Vec::new();
    for (k, v) in args {
        match v {
            Json::Null => {}
            Json::Array(items) => params.extend(items.iter().map(|i| (k.clone(), param_text(i)))),
            v => params.push((k.clone(), param_text(v))),
        }
    }
    params
}

/// What a tool calls.
enum Tool {
    Method(&'static Lexicon),
    Read(ops::Read),
    Own(Own),
}

/// Call a tool's method, with its arguments as the query's parameters or the
/// procedure's input, and the request's `Authorization` header, from `client`:
/// its answer, and whether it is an error the method answered. An MCP
/// session's access token makes the call its account's, with its scope, as
/// an OAuth access token makes an XRPC call; one the MCP issuer gave that no
/// longer works, or no token where the method needs one, is the challenge
/// that has the client sign in (`spec/OAUTH-MCP.md`).
async fn call_tool(
    st: &Shared,
    name: &str,
    arguments: Option<&Json>,
    authorization: Option<String>,
    client: String,
) -> Result<(Json, bool), RpcError> {
    let bearer = Bearer::of(authorization.as_deref());
    // A method's tool, one of the admin's reads', or one of the account's
    // OAuth routes'.
    let tool = match (
        pds_lexicon::by_tool(name),
        ops::Read::of_tool(name),
        Own::of_tool(name),
    ) {
        (Some(m), _, _) => Tool::Method(m),
        (None, Some(read), _) => Tool::Read(read),
        (None, None, Some(own)) => Tool::Own(own),
        (None, None, None) => {
            return Err(rpc_err(
                StatusCode::OK,
                INVALID_PARAMS,
                format!("Unknown tool: {name}"),
            ));
        }
    };
    let mut args = match arguments {
        None | Some(Json::Null) => Map::new(),
        Some(Json::Object(a)) => a.clone(),
        Some(_) => {
            return Err(rpc_err(
                StatusCode::OK,
                INVALID_PARAMS,
                "arguments must be an object",
            ));
        }
    };
    let mcp = match bearer {
        Bearer::Token(t) => match crate::oauth::mcp::access(st, t) {
            McpToken::Not => None,
            McpToken::Gone => {
                return Err(challenge(
                    st,
                    Some("invalid_token"),
                    "The access token is expired, replaced or revoked",
                ));
            }
            McpToken::Good(a) => Some((t, a)),
        },
        _ => None,
    };
    let m = match tool {
        Tool::Method(m) => m,
        // The admin's reads, as XRPC answers them; a token, of an MCP session or
        // not, is no admin.
        Tool::Read(read) => {
            let params = query_params(&args);
            let call = Call {
                nsid: read.route(),
                method: &Method::GET,
                params: &params,
                body: &[],
                bearer,
                headers: &HeaderMap::new(),
                client,
                charged: OnceLock::new(),
                http: None,
            };
            return Ok(match ops::read(st, read, &call).await {
                Ok(a) => (a.json(), false),
                Err(e) => (json!({ "error": e.name, "message": e.message }), true),
            });
        }
        // The account's own routes, as XRPC answers them, a change's
        // arguments its JSON body: an MCP session's token is refused as an
        // OAuth access token is, and no token is the challenge.
        Tool::Own(own) => {
            let grant = mcp.map(|(_, a)| scopes::Grant {
                did: a.did,
                scope: scopes::Scope::of(&a.scope),
            });
            let method = own.method();
            let body = if method == Method::POST {
                Json::Object(args).to_string()
            } else {
                String::new()
            };
            let headers = HeaderMap::from_iter([(
                header::CONTENT_TYPE,
                HeaderValue::from_static(pds_lexicon::JSON),
            )]);
            let call = Call {
                nsid: own.name(),
                method: &method,
                params: &[],
                body: body.as_bytes(),
                bearer: grant.as_ref().map_or(bearer, Bearer::OAuth),
                headers: &headers,
                client,
                charged: OnceLock::new(),
                http: None,
            };
            return match account::answer(st, own, &call).await {
                Ok(j) => Ok((j, false)),
                Err(e) if authorization.is_none() && e.status == 401 && e.name == "AuthMissing" => {
                    Err(challenge(st, None, &e.message))
                }
                Err(e) => Ok((json!({ "error": e.name, "message": e.message }), true)),
            };
        }
    };
    // The token's scope, for a step-up if the call is refused for it.
    let granted = mcp.as_ref().map(|(_, a)| a.scope.clone());
    // A `repo` or `did` left out is the token's account's; with no token, or
    // one the server did not give out, it stays out, for the method to answer.
    let did = match &mcp {
        Some((_, a)) => Some(a.did.clone()),
        None => match st.auth(bearer) {
            Auth::Account(did) => Some(did),
            _ => None,
        },
    };
    if let Some(did) = did {
        for a in m.args.iter().filter(|a| a.names_account()) {
            args.entry(a.name.clone()).or_insert_with(|| json!(did));
        }
    }
    // What else a write needs that the token lacks, for a step-up to name.
    let also = granted
        .as_deref()
        .map(|g| scopes::missing_for_records(&m.nsid, &args, g))
        .unwrap_or_default();
    let (method, mut params, mut body) = (
        if m.kind == Kind::Query {
            Method::GET
        } else {
            Method::POST
        },
        Vec::new(),
        String::new(),
    );
    if m.kind == Kind::Query {
        params = query_params(&args);
    } else if m.input.is_some() || !args.is_empty() {
        // A procedure that takes no input is sent none, unless given arguments, which it refuses.
        body = Json::Object(args).to_string();
    }
    let mut headers = HeaderMap::new();
    if let Some(v) = authorization
        .as_deref()
        .and_then(|a| HeaderValue::from_str(a).ok())
    {
        headers.insert(header::AUTHORIZATION, v);
    }
    let mut grant = None;
    let mut call = Call {
        nsid: &m.nsid,
        method: &method,
        params: &params,
        body: body.as_bytes(),
        bearer,
        headers: &headers,
        client,
        charged: OnceLock::new(),
        http: None,
    };
    if let Some((token, access)) = mcp {
        match scopes::look_mcp(st, &call, access) {
            Ok(Some(g)) => grant = Some(g),
            // A method that reads no OAuth token answers it as XRPC answers one sent so.
            Ok(None) => call.bearer = Bearer::DPoP(token),
            Err(e) => {
                if let Some(s) = granted.as_deref().and_then(|g| step_up(st, g, &also, &e)) {
                    return Err(s);
                }
                return Ok((json!({ "error": e.name, "message": e.message }), true));
            }
        }
    }
    if let Some(g) = &grant {
        call.bearer = Bearer::OAuth(g);
    }
    let (content, is_error) = match answer(st, &call).await {
        // A service's error is the method's, as it answered it.
        Ok(Resp::Upstream(u)) if u.status >= 400 => (
            serde_json::from_slice(&u.body).unwrap_or_else(|_| json!({})),
            true,
        ),
        // A method that answers nothing answers `{}`.
        Ok(_) if m.output.is_none() => (json!({}), false),
        Ok(Resp::Json(j) | Resp::Headed(j, _)) => (j, false),
        Ok(Resp::Upstream(u)) => match serde_json::from_slice::<Json>(&u.body) {
            Ok(j) => (j, false),
            Err(_) => (
                json!({ "error": "InternalServerError", "message": "a service answered no JSON" }),
                true,
            ),
        },
        // No other method with a tool answers anything but JSON.
        Ok(
            Resp::Car(_)
            | Resp::CarStream(_)
            | Resp::Blob(_)
            | Resp::Nothing
            | Resp::Star(_)
            | Resp::Archive(..),
        ) => (
            json!({ "error": "InternalServerError", "message": "a tool's method answered no JSON" }),
            true,
        ),
        // No token, where the method needs an account's: a sign-in.
        Err(e) if authorization.is_none() && e.status == 401 && e.name == "AuthMissing" => {
            return Err(challenge(st, None, &e.message));
        }
        Err(e) => {
            if let Some(s) = granted.as_deref().and_then(|g| step_up(st, g, &also, &e)) {
                return Err(s);
            }
            (json!({ "error": e.name, "message": e.message }), true)
        }
    };
    Ok((content, is_error))
}

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

    #[test]
    fn origins() {
        for ok in [
            "http://localhost:2583",
            "http://127.0.0.1",
            "https://[::1]:8080",
            "http://localhost",
        ] {
            assert!(local_origin(&HeaderValue::from_static(ok)), "{ok}");
        }
        for bad in [
            "http://evil.example",
            "http://localhost.evil.example",
            "null",
            "http://127.0.0.1.nip.io:80",
        ] {
            assert!(!local_origin(&HeaderValue::from_static(bad)), "{bad}");
        }
    }

    /// A method that answers nothing is a tool answering `{}`; given
    /// arguments it takes none of, it refuses them as XRPC refuses a body.
    #[tokio::test]
    async fn no_answer_is_empty_object() {
        use crate::testing::*;
        let plc = plc().await;
        let dir = scratch("mcp-nothing");
        let s = open(&dir, &plc);
        create(&s, "alice").await;
        let got = call(
            &s,
            "com.atproto.server.createSession",
            None,
            json!({ "identifier": "alice.test", "password": "alice-pw" }),
        )
        .await
        .unwrap();
        let refresh = format!("Bearer {}", got["refreshJwt"].as_str().unwrap());
        let tool = |name: &'static str, args: Option<Json>| {
            let (s, refresh) = (s.clone(), refresh.clone());
            async move {
                match call_tool(&s, name, args.as_ref(), Some(refresh), "127.0.0.1".into()).await {
                    Ok(r) => r,
                    Err(e) => panic!("{name}: {}", e.message),
                }
            }
        };
        let (refused, is_error) = tool("server_delete_session", Some(json!({ "x": 1 }))).await;
        assert_eq!(
            (is_error, &refused["error"]),
            (true, &json!("InvalidRequest"))
        );
        for args in [None, Some(json!({}))] {
            assert_eq!(
                tool("server_delete_session", args).await,
                (json!({}), false)
            );
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The account's own routes are tools after the admin's reads, in
    /// order, answered as their routes answer: with no token, the challenge
    /// that has a client sign in.
    #[tokio::test]
    async fn oauth_tools() {
        use crate::testing::*;
        let all = tools();
        let last: Vec<&Json> = all[all.len() - 9..].iter().map(|t| &t["name"]).collect();
        assert_eq!(
            last,
            [
                "admin_logs",
                "admin_stats",
                "oauth_sessions",
                "oauth_revoke_session",
                "oauth_devices",
                "oauth_revoke_device",
                "passkey_list",
                "passkey_add",
                "passkey_remove"
            ]
        );
        let schema = |t: &Json| (t["inputSchema"].clone(), t["annotations"].clone());
        assert_eq!(
            schema(&all[all.len() - 4]),
            (
                json!({ "type": "object", "properties": { "id": { "type": "string" } }, "required": ["id"] }),
                json!({ "readOnlyHint": false, "destructiveHint": true })
            )
        );
        assert_eq!(
            schema(&all[all.len() - 3]),
            (
                json!({ "type": "object", "properties": {}, "required": [] }),
                json!({ "readOnlyHint": true })
            )
        );
        assert_eq!(
            schema(&all[all.len() - 2]),
            (
                json!({ "type": "object", "properties": { "name": { "type": "string", "minLength": 1, "maxLength": 64 } }, "required": ["name"] }),
                json!({ "readOnlyHint": false, "destructiveHint": false })
            )
        );
        assert_eq!(schema(&all[all.len() - 1]), schema(&all[all.len() - 4]));
        let plc = plc().await;
        let dir = scratch("mcp-oauth");
        let s = open(&dir, &plc);
        create(&s, "alice").await;
        let token = format!("Bearer {}", session(&s, "alice").await);
        let tool = |name: &'static str, args: Option<Json>, auth: Option<&str>| {
            let (s, auth) = (s.clone(), auth.map(str::to_string));
            async move { call_tool(&s, name, args.as_ref(), auth, "127.0.0.1".into()).await }
        };
        let answered = |r: Result<(Json, bool), RpcError>| match r {
            Ok(r) => r,
            Err(e) => panic!("{}", e.message),
        };
        assert_eq!(
            answered(tool("oauth_sessions", None, Some(&token)).await),
            (json!({ "sessions": [] }), false)
        );
        assert_eq!(
            answered(
                tool(
                    "oauth_revoke_device",
                    Some(json!({ "id": "x" })),
                    Some(&token)
                )
                .await
            ),
            (json!({}), false)
        );
        let (refused, is_error) = answered(tool("oauth_revoke_session", None, Some(&token)).await);
        assert_eq!(
            (is_error, &refused["error"]),
            (true, &json!("InvalidRequest"))
        );
        let (refused, is_error) =
            answered(tool("oauth_devices", None, Some("Basic YWRtaW46eA==")).await);
        assert_eq!(
            (is_error, &refused["error"]),
            (true, &json!("InvalidToken"))
        );
        let Err(e) = tool("oauth_sessions", None, None).await else {
            panic!("no challenge");
        };
        assert_eq!(e.status, StatusCode::UNAUTHORIZED);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Every tool has a title by the rule of `spec/COMMANDS.md`, "Names",
    /// and its hints as "Hints" gives them, by what it does.
    #[test]
    fn titles_and_hints() {
        let all = tools();
        let of = |name: &str| {
            all.iter()
                .find(|t| t["name"] == name)
                .unwrap_or_else(|| panic!("no tool {name}"))
        };
        assert!(all.iter().all(|t| t["title"].is_string()));
        for (name, title) in [
            (
                "identity_get_recommended_did_credentials",
                "Get recommended did credentials (identity)",
            ),
            ("repo_create_record", "Create record (repo)"),
            ("admin_logs", "Logs (admin)"),
            ("admin_stats", "Stats (admin)"),
            ("oauth_sessions", "Sessions (oauth)"),
            ("oauth_revoke_session", "Revoke session (oauth)"),
            ("oauth_devices", "Devices (oauth)"),
            ("oauth_revoke_device", "Revoke device (oauth)"),
            ("passkey_list", "List (passkey)"),
            ("passkey_add", "Add (passkey)"),
            ("passkey_remove", "Remove (passkey)"),
        ] {
            assert_eq!(of(name)["title"], title, "{name}");
        }
        let adds = json!({ "readOnlyHint": false, "destructiveHint": false });
        let destroys = json!({ "readOnlyHint": false, "destructiveHint": true });
        for (name, hints) in [
            ("server_get_service_auth", &adds),
            ("repo_create_record", &adds),
            ("repo_delete_record", &destroys),
            ("memberspace_put_members", &destroys),
            ("repo_list_records", &json!({ "readOnlyHint": true })),
        ] {
            assert_eq!(&of(name)["annotations"], hints, "{name}");
        }
    }

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