multicast 2.0.0

A declarative CLI framework for Rust with typed commands, agent discovery, HTTP, and MCP
Documentation
//! Prompt Guides and their compilers.
//!
//! A [`PromptGuide`] tells a model how to approach one kind of task with a
//! named set of Capabilities. It references those Capabilities by command path
//! only and never carries a handler, so registering, changing, or removing a
//! guide leaves every Tool Contract and every tool call unchanged.
//!
//! The compilers in this module lower guides into Prompt Artifacts: MCP
//! prompts and the `--llms-full` Markdown section.

use serde_json::{Value, json};

/// Name of the optional argument every published guide accepts.
pub const TASK_ARGUMENT: &str = "task";

/// Target-neutral guidance for one kind of task.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PromptGuide {
    /// Stable identity shared with the Capability that activates this guide.
    pub name: String,
    /// One-line neutral summary of the task this guide covers.
    pub summary: String,
    /// Imperative guidance for the model.
    pub instructions: String,
    /// Command paths, space separated for nested commands, that the guidance
    /// directs the model to use.
    pub capabilities: Vec<String>,
}

impl PromptGuide {
    /// Creates a guide from its parts.
    pub fn new(
        name: impl Into<String>,
        summary: impl Into<String>,
        instructions: impl Into<String>,
        capabilities: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self {
            name: name.into(),
            summary: summary.into(),
            instructions: instructions.into(),
            capabilities: capabilities.into_iter().map(Into::into).collect(),
        }
    }
}

/// Returns the MCP tool name for a command path.
pub(crate) fn mcp_tool_name(path: &str) -> String {
    path.split_whitespace().collect::<Vec<_>>().join("_")
}

/// Lowers a guide into its `prompts/list` entry.
pub(crate) fn mcp_prompt_entry(guide: &PromptGuide) -> Value {
    json!({
        "name": guide.name,
        "description": guide.summary,
        "arguments": [{
            "name": TASK_ARGUMENT,
            "description": "The task to focus on.",
            "required": false,
        }],
    })
}

/// Lowers a guide into its `prompts/get` result.
///
/// `exposed` reports whether the serving transport exposes an MCP tool name;
/// capabilities the server does not expose are left out of the listing.
pub(crate) fn mcp_prompt_result(
    guide: &PromptGuide,
    task: Option<&str>,
    exposed: impl Fn(&str) -> bool,
) -> Value {
    let tools = guide
        .capabilities
        .iter()
        .map(|path| mcp_tool_name(path))
        .filter(|name| exposed(name))
        .collect::<Vec<_>>();
    let mut text = guide.instructions.trim().to_string();
    if !tools.is_empty() {
        text.push_str("\n\nTools for this task: ");
        text.push_str(&tools.join(", "));
        text.push('.');
    }
    if let Some(task) = task.map(str::trim).filter(|task| !task.is_empty()) {
        text.push_str("\n\nTask: ");
        text.push_str(task);
    }
    json!({
        "description": guide.summary,
        "messages": [{
            "role": "user",
            "content": { "type": "text", "text": text },
        }],
    })
}

/// Lowers guides into the `--llms-full` Markdown section. Returns `None` when
/// there are no guides.
pub(crate) fn markdown_section(guides: &[PromptGuide]) -> Option<String> {
    if guides.is_empty() {
        return None;
    }
    let mut out = String::from("## Archetypes\n");
    for guide in guides {
        out.push_str(&format!("\n### {}\n\n{}\n\n", guide.name, guide.summary));
        out.push_str(guide.instructions.trim());
        out.push('\n');
        if !guide.capabilities.is_empty() {
            let names = guide
                .capabilities
                .iter()
                .map(|path| format!("`{path}`"))
                .collect::<Vec<_>>()
                .join(", ");
            out.push_str(&format!("\nCommands: {names}\n"));
        }
    }
    Some(out)
}

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

    fn guide() -> PromptGuide {
        PromptGuide::new(
            "triage",
            "Sort incoming reports",
            "  Read the report first.  ",
            ["read", "label set", "hidden"],
        )
    }

    #[test]
    fn mcp_result_lists_exposed_tools_and_task() {
        let result = mcp_prompt_result(&guide(), Some(" crash on start "), |name| name != "hidden");
        assert_eq!(
            result,
            json!({
                "description": "Sort incoming reports",
                "messages": [{
                    "role": "user",
                    "content": {
                        "type": "text",
                        "text": "Read the report first.\n\nTools for this task: read, label_set.\n\nTask: crash on start",
                    },
                }],
            })
        );
    }

    #[test]
    fn mcp_result_omits_blank_task_and_empty_listing() {
        let result = mcp_prompt_result(&guide(), Some("  "), |_| false);
        assert_eq!(
            result["messages"][0]["content"]["text"],
            "Read the report first."
        );
    }

    #[test]
    fn markdown_section_is_absent_without_guides() {
        assert_eq!(markdown_section(&[]), None);
        assert_eq!(
            markdown_section(&[guide()]).as_deref(),
            Some(
                "## Archetypes\n\n### triage\n\nSort incoming reports\n\nRead the report first.\n\nCommands: `read`, `label set`, `hidden`\n"
            )
        );
    }
}