pikopiko-cli 0.1.0

Command-line tool and MCP server to check, inspect, render and play MML with pikopiko.
Documentation
//! ツールに共通の部品。
//!
//! どのツールも「MML を検査する → 仕事をする → 検査の報告に結果を足して返す」の形なので、
//! 検査(`compile`)・報告の JSON(`report_json`)・仕事ができなかったときの結果(`failed`)・
//! 引数の誤り(`tool_error`)をここにまとめ、返す JSON の形をツールの間でそろえる。
//! AI が読む文は `tool_text` で `locales/<言語>/mcp.ftl` から作り、外のライブラリの文(英語)は出さない。
//! base64・16 進数・FNV-1a は依存を増やさないための小さな実装。

use super::*;

// ---- 共通の部品 ------------------------------------------------------------

/// 引数の誤りなど、「ツールを呼んだがうまくいかなかった」結果。AIが読んで直せるように文で返す。
pub(super) fn tool_error(message: impl Into<String>) -> CallToolResult {
    CallToolResult::structured_error(json!({ "ok": false, "error": message.into() }))
}

/// `mcp-*.ftl` のキーの文を、値(どれも文字列にして渡す)を入れて組み立てる。
pub(super) fn tool_text(i18n: &crate::text::Texts, key: &str, args: &[(&str, String)]) -> String {
    let args: Vec<(&str, pikopiko::lang::Arg)> =
        args.iter().map(|(k, v)| (*k, v.clone().into())).collect();
    i18n.tr_args(key, &args)
}

pub(super) fn resolve_dialect(
    name: Option<&str>,
    i18n: &crate::text::Texts,
) -> Result<Dialect, CallToolResult> {
    match name {
        None => Ok(Dialect::PIKOPIKO),
        Some(n) => Dialect::builtin(n).ok_or_else(|| {
            let names = Dialect::BUILTIN
                .iter()
                .map(|d| d.name)
                .collect::<Vec<_>>()
                .join(", ");
            tool_error(tool_text(
                i18n,
                "mcp-tool-unknown-dialect",
                &[("name", n.to_string()), ("names", names)],
            ))
        }),
    }
}

/// 検査まで済ませた MML。
pub(super) struct Compiled {
    pub(super) song: Option<Song>,
    pub(super) check: CheckReport,
}

pub(super) fn compile(
    mml: &str,
    dialect: Option<&str>,
    includes: Option<&std::collections::BTreeMap<String, String>>,
    libs: &[pikopiko::synth::tones::user::UserLibrary],
    i18n: &crate::text::Texts,
) -> Result<Compiled, CallToolResult> {
    // 共有の定義も含めた大きさで数える
    let total = mml.len() + includes.map_or(0, |m| m.iter().map(|(k, v)| k.len() + v.len()).sum());
    if total > MAX_SOURCE_BYTES {
        return Err(tool_error(tool_text(
            i18n,
            "mcp-tool-too-large",
            &[
                ("total", total.to_string()),
                ("max", MAX_SOURCE_BYTES.to_string()),
            ],
        )));
    }
    let dialect = resolve_dialect(dialect, i18n)?;
    let sources = pikopiko::compiler::include::Sources::new(
        includes
            .into_iter()
            .flatten()
            .map(|(k, v)| (k.clone(), v.clone())),
    );
    let loader = pikopiko::synth::tones::user::WithLibraries::new(Some(&sources), libs);
    let opts = CompileOptions {
        dialect,
        synths: pikopiko::synth::all(),
        include: Some(&loader),
        ..Default::default()
    };
    let (song, diags) = pikopiko::compile_with(mml, &opts);
    // 診断の文は言語に合わせる(キーと値は JSON の `key`・`args` に残る)
    Ok(Compiled {
        song,
        check: CheckReport::new(diags)
            .in_lang(i18n.lang())
            .with_messages(|d| i18n.diagnostic(d)),
    })
}

impl PikoServer {
    /// MML を検査し、曲にできたら曲と検査の報告を返す(引数は `compile` と同じ)。MML にエラーが
    /// あれば、`what`(できなかった仕事の文のキー `mcp-tool-what-…`)の仕事ができなかった結果
    /// (診断つき)を返す。曲を使うツール(`describe`・`build`・`render`・`edit_timbre`)の入口。
    pub(super) fn compile_song(
        &self,
        mml: &str,
        dialect: Option<&str>,
        includes: Option<&std::collections::BTreeMap<String, String>>,
        what: &str,
    ) -> Result<(Song, CheckReport), CallToolResult> {
        let c = compile(mml, dialect, includes, &self.config.tones, &self.i18n)?;
        match c.song {
            Some(song) => Ok((song, c.check)),
            None => Err(failed(&c.check, what, &self.i18n)),
        }
    }
}

/// 検査の報告に、ツール固有の項目を足した JSON。
pub(super) fn report_json(check: &CheckReport, extra: Vec<(&str, Value)>) -> Value {
    let mut m = match serde_json::to_value(check) {
        Ok(Value::Object(m)) => m,
        _ => Map::new(),
    };
    for (k, v) in extra {
        m.insert(k.to_string(), v);
    }
    Value::Object(m)
}

/// MML にエラーがあって、ツールの仕事ができなかったときの結果(診断つき)。
/// `what` は、できなかった仕事の文のキー(`mcp-tool-what-…`)。
pub(super) fn failed(check: &CheckReport, what: &str, i18n: &crate::text::Texts) -> CallToolResult {
    let message = tool_text(
        i18n,
        "mcp-tool-failed",
        &[
            ("what", i18n.tr(what)),
            ("errors", check.errors.to_string()),
        ],
    );
    CallToolResult::structured_error(report_json(check, vec![("error", Value::String(message))]))
}

pub(super) use crate::inline::base64;

/// FNV-1a(ファイル名を入力から決めるための簡単なハッシュ)。
pub(super) fn fnv1a(parts: &[&[u8]]) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for p in parts {
        for &b in *p {
            h ^= u64::from(b);
            h = h.wrapping_mul(0x0000_0100_0000_01b3);
        }
        h ^= 0xff; // 区切り
        h = h.wrapping_mul(0x0000_0100_0000_01b3);
    }
    h
}

pub(super) fn valid_file_name(n: &str) -> bool {
    (1..=64).contains(&n.len())
        && n.chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}