pikopiko-cli 0.1.0

Command-line tool and MCP server to check, inspect, render and play MML with pikopiko.
Documentation
//! MCP の resources と prompts。
//!
//! resources は読むだけの本文で、ツールと同じ内容を先読みできる形で出す:文法の仕様
//! (`pikopiko://spec`)、音源の説明(`pikopiko://synths`・`pikopiko://synths/<名前>`)、
//! 音色集のファイル(`pikopiko://tones/<音源>/<名前>`)、取扱説明書の 2 ページ(`pikopiko://guide/mml`・`guide/ai`。日本語)。
//! 仕様・音源・音色集の中身はツール(`get_spec`・`list_synths`・`get_tones`)と同じ関数・同じ言語で作るので、二重に管理しない。tools は 10 のままで、
//! resources を使えないクライアントも困らない。
//!
//! prompts は引数つきの手順のテンプレート(`compose`・`fix_diagnostics`・`design_timbre`)。
//! 本文と説明は `locales/<言語>/mcp.ftl` の `mcp-prompt-…`・`mcp-resource-…`(言語は `Config::lang`)。
//! ここの関数は `ServerHandler`(`router.rs`)から呼ぶ。同期の関数にしてテストしやすくしてある。

use rmcp::model::{Prompt, PromptArgument, PromptMessage, Resource, Role};

use super::*;

const SCHEME: &str = "pikopiko://";
const MIME_MD: &str = "text/markdown";
const MIME_JSON: &str = "application/json";
const MIME_MML: &str = "text/plain";

/// resource にする取扱説明書のページ(名前、本文)。正本は `docs/guide/` で、クレートの外を読めない
/// ので写しをここに置く(`scripts/release.sh sync`。`tests/guide_copy.rs` が見張る)。日本語だけ。
const GUIDES: [(&str, &str); 2] = [
    ("mml", include_str!("../../guide/mml.md")),
    ("ai", include_str!("../../guide/ai.md")),
];

impl PikoServer {
    /// 読める resources の一覧。
    pub(super) fn resource_list(&self) -> Vec<Resource> {
        let mut v = vec![
            Resource::new(format!("{SCHEME}spec"), "spec")
                .with_description(self.tr("mcp-resource-spec", &[]))
                .with_mime_type(MIME_MD),
            Resource::new(format!("{SCHEME}synths"), "synths")
                .with_description(self.tr("mcp-resource-synths", &[]))
                .with_mime_type(MIME_JSON),
        ];
        for (name, _) in GUIDES {
            v.push(
                Resource::new(format!("{SCHEME}guide/{name}"), format!("guide/{name}"))
                    .with_description(self.tr(&format!("mcp-resource-guide-{name}"), &[]))
                    .with_mime_type(MIME_MD),
            );
        }
        for s in pikopiko::synth::all() {
            v.push(
                Resource::new(
                    format!("{SCHEME}synths/{}", s.name),
                    format!("synths/{}", s.name),
                )
                .with_description(self.tr("mcp-resource-synth", &[("name", s.name.to_string())]))
                .with_mime_type(MIME_JSON),
            );
            for f in s.tone_files {
                v.push(
                    Resource::new(
                        format!("{SCHEME}tones/{}/{}", s.library_prefix(), f.name),
                        format!("tones/{}/{}", s.library_prefix(), f.name),
                    )
                    .with_description(self.tr(
                        "mcp-resource-tone",
                        &[("file", format!("@{}/{}", s.library_prefix(), f.name))],
                    ))
                    .with_mime_type(MIME_MML),
                );
            }
        }
        v
    }

    /// `uri` の本文と MIME 型。知らない URI は `None`。
    pub(super) fn resource_read(&self, uri: &str) -> Option<(&'static str, String)> {
        let path = uri.strip_prefix(SCHEME)?;
        match path {
            "spec" => Some((MIME_MD, pikopiko::spec_for(self.config.lang).to_string())),
            "synths" => Some((MIME_JSON, self.synths_json(None)?)),
            _ => {
                if let Some(name) = path.strip_prefix("guide/") {
                    let (_, text) = GUIDES.iter().find(|(n, _)| *n == name)?;
                    return Some((MIME_MD, (*text).to_string()));
                }
                if let Some(name) = path.strip_prefix("synths/") {
                    return Some((MIME_JSON, self.synths_json(Some(name))?));
                }
                let (synth, name) = path.strip_prefix("tones/")?.split_once('/')?;
                let spec = pikopiko::synth::find(pikopiko::synth::all(), synth)?;
                let file = spec.tone_file(name)?;
                let text = pikopiko::synth::tones::file_text(spec, file, self.i18n.lang());
                Some((MIME_MML, text))
            }
        }
    }

    fn synths_json(&self, only: Option<&str>) -> Option<String> {
        let all = pikopiko::synth::all();
        let one;
        let list: &[&pikopiko::synth::SynthSpec] = match only {
            None => all,
            Some(n) => {
                one = [pikopiko::synth::find(all, n)?];
                &one
            }
        };
        let i18n = &self.i18n;
        let cat = synth_catalog_with(list, i18n.lang(), &mut |k| i18n.override_text(k));
        serde_json::to_string_pretty(&json!({ "synths": cat })).ok()
    }

    /// prompts の一覧。
    pub(super) fn prompt_list(&self) -> Vec<Prompt> {
        let arg = |name: &str, required: bool| {
            let mut a = PromptArgument::new(name)
                .with_description(self.tr(&format!("mcp-prompt-arg-{name}"), &[]));
            a.required = Some(required);
            a
        };
        let p = |name: &str, args: Vec<PromptArgument>| {
            Prompt::new(
                name,
                Some(self.tr(&format!("mcp-prompt-{name}"), &[])),
                Some(args),
            )
        };
        vec![
            p(
                "compose",
                vec![
                    arg("genre", true),
                    arg("tempo", false),
                    arg("length", false),
                ],
            ),
            p("fix_diagnostics", vec![arg("mml", true)]),
            p(
                "design_timbre",
                vec![arg("sound", true), arg("synth", false)],
            ),
        ]
    }

    /// prompt の本文(1 つのユーザーのメッセージ)。足りない必須の引数・知らない名前は `Err`(文)。
    pub(super) fn prompt_get(
        &self,
        name: &str,
        args: &Map<String, Value>,
    ) -> Result<(String, Vec<PromptMessage>), String> {
        let get = |k: &str| args.get(k).and_then(Value::as_str).map(str::to_string);
        let need = |k: &str| {
            get(k).filter(|s| !s.trim().is_empty()).ok_or_else(|| {
                self.tr(
                    "mcp-prompt-missing-arg",
                    &[("prompt", name.to_string()), ("arg", k.to_string())],
                )
            })
        };
        let body = match name {
            "compose" => self.tr(
                "mcp-prompt-body-compose",
                &[
                    ("genre", need("genre")?),
                    ("tempo", get("tempo").unwrap_or_default()),
                    ("length", get("length").unwrap_or_default()),
                ],
            ),
            "fix_diagnostics" => {
                self.tr("mcp-prompt-body-fix_diagnostics", &[("mml", need("mml")?)])
            }
            "design_timbre" => self.tr(
                "mcp-prompt-body-design_timbre",
                &[
                    ("sound", need("sound")?),
                    ("synth", get("synth").unwrap_or_else(|| "va".into())),
                ],
            ),
            _ => {
                let names: Vec<String> = self.prompt_list().into_iter().map(|p| p.name).collect();
                return Err(self.tr(
                    "mcp-prompt-unknown",
                    &[("name", name.to_string()), ("names", names.join(", "))],
                ));
            }
        };
        let description = self.tr(&format!("mcp-prompt-{name}"), &[]);
        Ok((description, vec![PromptMessage::new_text(Role::User, body)]))
    }
}