pikopiko-cli 0.1.0

Command-line tool and MCP server to check, inspect, render and play MML with pikopiko.
Documentation
//! リモート MCP(Streamable HTTP):`pikopiko-mcp --http <アドレス:ポート>`(`mcp-http` 機能)。
//!
//! 何のためにあるか:Web 版・モバイル版の AI は手元のアプリではないので標準入出力で呼べない。
//! 利用者が自分で動かすサーバーとして HTTP で受ける。ツール・resources・prompts は標準入出力と
//! 同じ([`PikoServer`] を共有する)。
//!
//! 約束:
//! - **セッションを持たない**(ステートレス、`json_response`):1 回の呼び出しが 1 回の POST で終わり、
//!   サーバーに状態を残さない。
//! - **ファイルを書かない**:[`Config::write_files`] を `false` にして使う(音は結果に埋めて返す)。
//!   書き出し先を外から埋められないようにするため。
//! - **認証**:`Authorization: Bearer <トークン>`。トークンなしで受けてよいのは自分のマシン
//!   (ループバック)だけ([`HttpOptions::validate`])。比較は時間によらない。
//! - **重さの上限**:同時に処理する数([`HttpOptions::max_concurrency`])を超えたら `503`。1 回の
//!   書き出しの長さは [`Config::max_render_secs`]。
//! - **`Host` の検査**:既定は自分のマシンの名前だけ。外へ出すときは [`HttpOptions::allowed_hosts`] に
//!   使う名前(`host` か `host:port`)を足す(DNS リバインディングの対策。rmcp の検査)。
//! - TLS は持たない。必要ならリバースプロキシで終わらせる。

use std::convert::Infallible;
use std::future::Future;
use std::net::SocketAddr;
use std::sync::Arc;

use http_body_util::{BodyExt, Full};
use hyper::body::Bytes;
use hyper::service::service_fn;
use hyper::{Request, Response, StatusCode};
use hyper_util::rt::TokioIo;
use rmcp::transport::streamable_http_server::session::never::NeverSessionManager;
use rmcp::transport::{StreamableHttpServerConfig, StreamableHttpService};
use subtle::ConstantTimeEq;
use tokio::net::TcpListener;
use tokio::sync::Semaphore;

use super::{Config, PikoServer};

/// 同時に処理する数の既定。
pub const DEFAULT_MAX_CONCURRENCY: usize = 4;

/// HTTP で受けるときの設定。
#[derive(Debug, Clone)]
pub struct HttpOptions {
    /// 待ち受けるアドレスとポート。
    pub addr: SocketAddr,
    /// 固定のトークン(`Authorization: Bearer`)。`None` なら認証なし(ループバックだけ)。
    pub token: Option<String>,
    /// `Host` として受ける名前を足す(`example.com`・`example.com:8080`)。
    pub allowed_hosts: Vec<String>,
    /// 同時に処理する数(1 以上)。超えたら `503`。
    pub max_concurrency: usize,
}

/// 設定の誤り。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HttpOptionsError {
    /// ループバックでないアドレスで、トークンがない。
    TokenRequired,
    /// トークンが空。
    EmptyToken,
    /// 同時に処理する数が 0。
    BadConcurrency,
}

impl HttpOptions {
    /// 設定を確かめる:自分のマシン以外へ開くときはトークンが要る。
    pub fn validate(&self) -> Result<(), HttpOptionsError> {
        if self.token.as_deref() == Some("") {
            return Err(HttpOptionsError::EmptyToken);
        }
        if self.max_concurrency == 0 {
            return Err(HttpOptionsError::BadConcurrency);
        }
        if self.token.is_none() && !self.addr.ip().is_loopback() {
            return Err(HttpOptionsError::TokenRequired);
        }
        Ok(())
    }
}

/// 待ち受けを始めたサーバー。
pub struct HttpServer {
    listener: TcpListener,
    options: HttpOptions,
}

impl HttpServer {
    /// アドレスを開く(ポート 0 なら空いているポート。[`HttpServer::local_addr`] で確かめる)。
    pub async fn bind(options: HttpOptions) -> std::io::Result<Self> {
        let listener = TcpListener::bind(options.addr).await?;
        Ok(HttpServer { listener, options })
    }

    /// 実際に待ち受けているアドレス。
    pub fn local_addr(&self) -> std::io::Result<SocketAddr> {
        self.listener.local_addr()
    }

    /// `shutdown` が終わるまで受け続ける。
    ///
    /// `config` の `write_files` はここで `false` にする(HTTP ではファイルを書かない)。
    pub async fn serve(
        self,
        mut config: Config,
        shutdown: impl Future<Output = ()>,
    ) -> std::io::Result<()> {
        config.write_files = false;
        let mut http = StreamableHttpServerConfig::default()
            .with_legacy_session_mode(false)
            .with_json_response(true)
            .with_sse_keep_alive(None);
        if !self.options.allowed_hosts.is_empty() {
            let mut hosts = http.allowed_hosts.clone();
            hosts.extend(self.options.allowed_hosts.iter().cloned());
            http = http.with_allowed_hosts(hosts);
        }
        let service = Arc::new(StreamableHttpService::new(
            move || Ok(PikoServer::new(config.clone())),
            Arc::new(NeverSessionManager::default()),
            http,
        ));
        let token: Option<Arc<[u8]>> = self.options.token.as_deref().map(|t| t.as_bytes().into());
        let permits = Arc::new(Semaphore::new(self.options.max_concurrency));
        tokio::pin!(shutdown);
        loop {
            let (stream, _) = tokio::select! {
                r = self.listener.accept() => r?,
                () = &mut shutdown => return Ok(()),
            };
            let (service, token, permits) = (service.clone(), token.clone(), permits.clone());
            tokio::spawn(async move {
                let handler = service_fn(move |req: Request<hyper::body::Incoming>| {
                    let (service, token, permits) =
                        (service.clone(), token.clone(), permits.clone());
                    async move {
                        Ok::<_, Infallible>(
                            respond(&service, token.as_deref(), &permits, req).await,
                        )
                    }
                });
                // 接続ごとの誤り(相手が切ったなど)は、そのまま捨てる
                let _ = hyper::server::conn::http1::Builder::new()
                    .serve_connection(TokioIo::new(stream), handler)
                    .await;
            });
        }
    }
}

type Body = http_body_util::combinators::BoxBody<Bytes, Infallible>;

/// 1 つの要求を処理する:トークン → 同時数 → rmcp。
async fn respond(
    service: &StreamableHttpService<PikoServer, NeverSessionManager>,
    token: Option<&[u8]>,
    permits: &Semaphore,
    req: Request<hyper::body::Incoming>,
) -> Response<Body> {
    if let Some(token) = token {
        if !bearer_matches(req.headers(), token) {
            return plain(StatusCode::UNAUTHORIZED, "unauthorized")
                .tap_header("www-authenticate", "Bearer");
        }
    }
    let Ok(_permit) = permits.try_acquire() else {
        return plain(StatusCode::SERVICE_UNAVAILABLE, "busy").tap_header("retry-after", "1");
    };
    service.handle(req).await
}

/// `Authorization: Bearer <トークン>` が合うか(時間によらない比較)。
fn bearer_matches(headers: &hyper::HeaderMap, token: &[u8]) -> bool {
    headers
        .get(hyper::header::AUTHORIZATION)
        .and_then(|v| v.as_bytes().strip_prefix(b"Bearer "))
        .is_some_and(|given| bool::from(given.ct_eq(token)))
}

fn plain(status: StatusCode, text: &'static str) -> Response<Body> {
    let mut r = Response::new(Full::new(Bytes::from_static(text.as_bytes())).boxed());
    *r.status_mut() = status;
    r
}

/// 応答にヘッダーを 1 つ足す小さな道具。
trait TapHeader {
    fn tap_header(self, name: &'static str, value: &'static str) -> Self;
}

impl TapHeader for Response<Body> {
    fn tap_header(mut self, name: &'static str, value: &'static str) -> Self {
        self.headers_mut().insert(
            hyper::header::HeaderName::from_static(name),
            hyper::header::HeaderValue::from_static(value),
        );
        self
    }
}

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

    fn opts(addr: &str, token: Option<&str>, n: usize) -> HttpOptions {
        HttpOptions {
            addr: addr.parse().unwrap(),
            token: token.map(str::to_string),
            allowed_hosts: vec![],
            max_concurrency: n,
        }
    }

    #[test]
    fn open_address_needs_a_token() {
        assert_eq!(opts("127.0.0.1:0", None, 1).validate(), Ok(()));
        assert_eq!(opts("[::1]:0", None, 1).validate(), Ok(()));
        assert_eq!(
            opts("0.0.0.0:8080", None, 1).validate(),
            Err(HttpOptionsError::TokenRequired)
        );
        assert_eq!(opts("0.0.0.0:8080", Some("t"), 1).validate(), Ok(()));
        assert_eq!(
            opts("127.0.0.1:0", Some(""), 1).validate(),
            Err(HttpOptionsError::EmptyToken)
        );
        assert_eq!(
            opts("127.0.0.1:0", None, 0).validate(),
            Err(HttpOptionsError::BadConcurrency)
        );
    }

    #[test]
    fn bearer_must_match_exactly() {
        let mut h = hyper::HeaderMap::new();
        assert!(!bearer_matches(&h, b"abc"));
        h.insert("authorization", "Bearer abc".parse().unwrap());
        assert!(bearer_matches(&h, b"abc"));
        assert!(!bearer_matches(&h, b"abd"));
        assert!(!bearer_matches(&h, b"ab"));
        h.insert("authorization", "Basic abc".parse().unwrap());
        assert!(!bearer_matches(&h, b"abc"));
    }
}