pikopiko-cli 0.1.0

Command-line tool and MCP server to check, inspect, render and play MML with pikopiko.
Documentation
//! MCP の口:ツールの宣言(`#[tool_router]`)、言語に合わせた説明の差し替え、`ServerHandler`。
//!
//! rmcp のマクロはツールの説明をソースの文字列で持つので、ここでは名前だけを書き、
//! `localized_router` で `pikopiko::report::tools` の文(英語・日本語)に差し替える。
//! こうすると、スタジオの AI 連携と同じ説明の文を 1 か所(`locales/tools-*.ftl`)で直せる。
//! 差し替える言語は `schema_lang`:既定は英語、`PIKOPIKO_MCP_LOCALIZE_SCHEMA` のときだけ表示の
//! 言語(lingokit の約束。lingokit の `localize` は使う側の `.ftl` の `mcp-tool-<名前>` を引くが、
//! 説明の文の正本は本体の `tools-*.ftl` なので、切り替えの判定だけを lingokit から使う)。
//! 処理の中身は `tools` にあり、ここは引数を受けて渡すだけにしている。

use super::*;
use rmcp::model::{
    GetPromptRequestParams, GetPromptResponse, GetPromptResult, ListPromptsResult,
    ListResourcesResult, PaginatedRequestParams, ReadResourceRequestParams, ReadResourceResponse,
    ReadResourceResult, ResourceContents,
};
use rmcp::service::RequestContext;
use rmcp::RoleServer;

/// ツールと引数の説明・使い方の案内の言語:既定は英語、[`schema_localization_enabled`] のときだけ
/// 表示の言語 `lang`。
pub(super) fn schema_lang(lang: &'static str) -> &'static str {
    if schema_localization_enabled() {
        lang
    } else {
        "en"
    }
}

/// 言語に合わせて、ツールと引数の説明を差し替えたツールの一覧。説明の文は `pikopiko` の
/// `locales/tools-*.ftl`(`pikopiko::report::tools`。スタジオの AI 連携と同じ文)。
pub(super) fn localized_router(lang: &str) -> ToolRouter<PikoServer> {
    let mut router = PikoServer::tool_router();
    let texts = pikopiko::report::tools::for_lang(lang);
    for (name, route) in router.map.iter_mut() {
        let description = match name.as_ref() {
            "get_spec" => texts.get_spec,
            "list_synths" => texts.list_synths,
            "check_mml" => texts.check_mml,
            "describe_mml" => texts.describe_mml,
            "build_mml" => texts.build_mml,
            "render_mml" => texts.render_mml,
            "edit_timbre" => texts.edit_timbre,
            "measure_tone" => texts.measure_tone,
            "get_tones" => texts.get_tones,
            "format_mml" => texts.format_mml,
            _ => continue,
        };
        route.attr.description = Some(Cow::Borrowed(description));
        let mut schema = (*route.attr.input_schema).clone();
        if let Some(Value::Object(props)) = schema.get_mut("properties") {
            for (prop, v) in props.iter_mut() {
                if let (Some(d), Value::Object(o)) = (pikopiko::report::tools::param(prop, lang), v)
                {
                    o.insert("description".into(), Value::String(d.into()));
                }
            }
        }
        route.attr.input_schema = Arc::new(schema);
    }
    router
}

#[tool_router]
impl PikoServer {
    /// MML 文法仕様の全文(Markdown)を返す。MML を書く前に1回読む。
    #[tool(
        description = "get_spec",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    pub(super) async fn get_spec(&self) -> Result<CallToolResult, McpError> {
        Ok(CallToolResult::success(vec![ContentBlock::text(
            pikopiko::spec_for(self.config.lang),
        )]))
    }

    #[tool(
        description = "list_synths",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    pub(super) async fn list_synths(
        &self,
        args: Parameters<ListSynthsArgs>,
    ) -> Result<CallToolResult, McpError> {
        Ok(self.do_list_synths(&args.0))
    }

    #[tool(
        description = "get_tones",
        annotations(read_only_hint = true, idempotent_hint = true, open_world_hint = false)
    )]
    pub(super) async fn get_tones(
        &self,
        args: Parameters<GetTonesArgs>,
    ) -> Result<CallToolResult, McpError> {
        Ok(self.do_get_tones(&args.0))
    }

    #[tool(
        description = "format_mml",
        annotations(read_only_hint = true, idempotent_hint = true, open_world_hint = false)
    )]
    pub(super) async fn format_mml(
        &self,
        args: Parameters<FormatArgs>,
    ) -> Result<CallToolResult, McpError> {
        Ok(self.do_format(&args.0))
    }

    #[tool(
        description = "check_mml",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    pub(super) async fn check_mml(
        &self,
        args: Parameters<MmlArgs>,
    ) -> Result<CallToolResult, McpError> {
        Ok(self.do_check(&args.0))
    }

    #[tool(
        description = "describe_mml",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    pub(super) async fn describe_mml(
        &self,
        args: Parameters<MmlArgs>,
    ) -> Result<CallToolResult, McpError> {
        Ok(self.do_describe(&args.0))
    }

    #[tool(
        description = "build_mml",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    pub(super) async fn build_mml(
        &self,
        args: Parameters<BuildArgs>,
    ) -> Result<CallToolResult, McpError> {
        Ok(self.do_build(&args.0))
    }

    #[tool(
        description = "edit_timbre",
        annotations(read_only_hint = true, idempotent_hint = true, open_world_hint = false)
    )]
    pub(super) async fn edit_timbre(
        &self,
        args: Parameters<EditTimbreArgs>,
    ) -> Result<CallToolResult, McpError> {
        Ok(self.do_edit_timbre(&args.0))
    }

    #[tool(
        description = "measure_tone",
        annotations(
            read_only_hint = false,
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    pub(super) async fn measure_tone(
        &self,
        args: Parameters<MeasureToneArgs>,
    ) -> Result<CallToolResult, McpError> {
        Ok(self.do_measure_tone(&args.0))
    }

    #[tool(
        description = "render_mml",
        annotations(
            read_only_hint = false,
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    pub(super) async fn render_mml(
        &self,
        args: Parameters<RenderArgs>,
    ) -> Result<CallToolResult, McpError> {
        // 長い曲の書き出しで、ほかのリクエストを止めないように専用のスレッドで行う
        let this = self.clone();
        let args = args.0;
        tokio::task::spawn_blocking(move || this.do_render(&args))
            .await
            .map_err(|_| {
                // tokio の文(英語)は出さない
                McpError::internal_error(self.tr("mcp-tool-render-aborted", &[]), None)
            })
    }
}

#[tool_handler(router = self.router)]
impl ServerHandler for PikoServer {
    async fn list_resources(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListResourcesResult, McpError> {
        Ok(ListResourcesResult::with_all_items(self.resource_list()))
    }

    async fn read_resource(
        &self,
        request: ReadResourceRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<ReadResourceResponse, McpError> {
        match self.resource_read(&request.uri) {
            Some((mime, text)) => {
                Ok(ReadResourceResult::new(vec![
                    ResourceContents::text(text, request.uri).with_mime_type(mime)
                ])
                .into())
            }
            None => Err(McpError::resource_not_found(
                self.tr("mcp-resource-not-found", &[("uri", request.uri.clone())]),
                None,
            )),
        }
    }

    async fn list_prompts(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListPromptsResult, McpError> {
        Ok(ListPromptsResult::with_all_items(self.prompt_list()))
    }

    async fn get_prompt(
        &self,
        request: GetPromptRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<GetPromptResponse, McpError> {
        let args = request.arguments.unwrap_or_default();
        match self.prompt_get(&request.name, &args) {
            Ok((description, messages)) => Ok(GetPromptResult::new(messages)
                .with_description(description)
                .into()),
            Err(text) => Err(McpError::invalid_params(text, None)),
        }
    }

    fn get_info(&self) -> ServerConfig {
        ServerConfig::new(
            ServerCapabilities::builder()
                .enable_tools()
                .enable_resources()
                .enable_prompts()
                .build(),
        )
        .with_server_info(Implementation::new(
            "pikopiko-mcp",
            env!("CARGO_PKG_VERSION"),
        ))
        .with_instructions(pikopiko::report::tools::for_lang(schema_lang(self.config.lang)).guide)
    }
}