offline-generator 0.4.0

Project scaffolding engine for the Offline Protocol CLI (Tera-based)
Documentation
//! `.mcp.json` and `AGENTS.md` wiring shared by `offline init` and the MCP
//! `init_project` tool.
//!
//! The generated `.mcp.json` starts this release's MCP server through npx, so
//! it works without a global `offline` install. An existing `.mcp.json` is
//! never rewritten; the `AGENTS.md` note only claims the server is registered
//! there when that file actually registers it.

use serde_json::{json, Value};

/// Server name used in generated MCP configs.
pub const MCP_SERVER_NAME: &str = "offline-protocol";

/// The `.mcp.json` document this release writes for a project.
pub fn mcp_json() -> Value {
    let (command, args) = offline_registry::mcp_serve_command();
    json!({
        "mcpServers": {
            MCP_SERVER_NAME: {"command": command, "args": args}
        }
    })
}

/// Whether an existing `.mcp.json` already starts an Offline Protocol MCP
/// server: an `offline-protocol` entry, `offline mcp serve`, or the
/// `@offline-protocol/cli` package through npx.
pub fn registers_offline_mcp(existing: &str) -> bool {
    let Ok(doc) = serde_json::from_str::<Value>(existing) else {
        return false;
    };
    let Some(servers) = doc.get("mcpServers").and_then(Value::as_object) else {
        return false;
    };
    servers.iter().any(|(name, server)| {
        if name == MCP_SERVER_NAME {
            return true;
        }
        let command = server.get("command").and_then(Value::as_str).unwrap_or("");
        let args: Vec<&str> = server
            .get("args")
            .and_then(Value::as_array)
            .map(|a| a.iter().filter_map(Value::as_str).collect())
            .unwrap_or_default();
        let serves_mcp = args.windows(2).any(|w| w == ["mcp", "serve"]);
        serves_mcp
            && (command == "offline"
                || args
                    .iter()
                    .any(|a| a.starts_with(offline_registry::CLI_NPM_PACKAGE)))
    })
}

/// Where the Offline Protocol MCP server stands for a project after init.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum McpRegistration {
    /// `.mcp.json` was written by this run.
    Written,
    /// An existing `.mcp.json` already registers the server.
    AlreadyRegistered,
    /// An existing `.mcp.json` was left untouched and does not register it.
    NotRegistered,
}

/// Heading that marks the section this module appends to `AGENTS.md`.
pub const AGENTS_HEADING: &str = "## Offline Protocol";

/// Whether an existing `AGENTS.md` already carries Offline Protocol guidance.
pub fn agents_has_section(existing: &str) -> bool {
    existing.lines().any(|l| l.trim() == AGENTS_HEADING) || existing.contains("offline mcp serve")
}

/// The `AGENTS.md` section for a project.
pub fn agents_section(
    installed: &[String],
    skills: &[String],
    registration: McpRegistration,
) -> String {
    let command = offline_registry::mcp_serve_command_line();
    let mcp = match registration {
        McpRegistration::Written | McpRegistration::AlreadyRegistered => format!(
            "The Offline Protocol MCP server, with the full SDK knowledge base, is \
registered in `.mcp.json` (`{command}`). If your agent already has it from an \
Offline Protocol plugin, one copy is enough."
        ),
        McpRegistration::NotRegistered => format!(
            "This project's `.mcp.json` does not register the Offline Protocol MCP \
server. Add it to your agent with `{command}`, or install the Offline Protocol \
plugin, before relying on the MCP tools."
        ),
    };
    let mut s = format!(
        "\n{AGENTS_HEADING}\n\n\
This project uses the Offline Protocol ecosystem. {mcp}\n\n\
**Before writing any Offline Protocol SDK code**, read the relevant skill \
via the MCP `get_skill` tool or `offline skills show <name>`.\n"
    );
    if !installed.is_empty() {
        s.push_str("\nInstalled packages: ");
        s.push_str(&installed.join(", "));
        s.push('\n');
    }
    if !skills.is_empty() {
        s.push_str("Relevant skills: ");
        s.push_str(&skills.join(", "));
        s.push('\n');
    }
    s
}

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

    #[test]
    fn generated_config_uses_pinned_npx_package() {
        let doc = mcp_json();
        let server = &doc["mcpServers"][MCP_SERVER_NAME];
        assert_eq!(server["command"], "npx");
        let args: Vec<&str> = server["args"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert_eq!(
            args,
            [
                "-y",
                &format!("@offline-protocol/cli@{}", offline_registry::CLI_VERSION),
                "mcp",
                "serve"
            ]
        );
        assert!(registers_offline_mcp(&doc.to_string()));
    }

    #[test]
    fn detects_existing_registrations() {
        assert!(registers_offline_mcp(
            r#"{"mcpServers":{"op":{"command":"offline","args":["mcp","serve"]}}}"#
        ));
        assert!(registers_offline_mcp(
            r#"{"mcpServers":{"x":{"command":"npx","args":["-y","@offline-protocol/cli@0.2.2","mcp","serve"]}}}"#
        ));
        assert!(!registers_offline_mcp(
            r#"{"mcpServers":{"github":{"command":"npx","args":["-y","@modelcontextprotocol/server-github"]}}}"#
        ));
        assert!(!registers_offline_mcp("not json"));
    }

    #[test]
    fn agents_section_is_honest_about_registration() {
        let registered = agents_section(&[], &[], McpRegistration::Written);
        assert!(registered.contains("is registered in `.mcp.json`"));
        let missing = agents_section(&[], &[], McpRegistration::NotRegistered);
        assert!(missing.contains("does not register"));
        assert!(!missing.contains("is registered in"));
    }
}