use mcp_host::prelude::*;
use mcp_host::registry::router::McpToolRouter;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::json;
use toml::{Table, Value as TomlValue};
use super::super::McpState;
use super::insert_string;
use super::json_output;
use super::super::elicit;
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ManifestParams {
pub path: Option<String>,
pub project: String,
pub data_dir: Option<String>,
pub releases_dir: Option<String>,
pub zpool: Option<String>,
pub dataset: Option<String>,
#[serde(default)]
pub jails: Vec<JailParams>,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct JailParams {
pub name: String,
pub release: Option<String>,
pub path: Option<String>,
pub build: Option<String>,
pub jailfile: Option<String>,
pub hostname: Option<String>,
#[serde(default)]
pub depends_on: Vec<String>,
#[serde(default)]
pub tags: Vec<String>,
pub init: Option<bool>,
pub stop: Option<String>,
pub network: Option<NetworkParams>,
pub resources: Option<ResourceParams>,
#[serde(default)]
pub params: std::collections::BTreeMap<String, JailParamValue>,
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum JailParamValue {
Bool(bool),
Integer(i64),
Text(String),
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct NetworkParams {
#[serde(default)]
pub vnet: bool,
pub bridge: Option<String>,
pub ip_cidr: Option<String>,
pub ip: Option<String>,
pub gateway: Option<String>,
#[serde(default)]
pub nameservers: Vec<String>,
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ResourceParams {
pub memory: Option<String>,
pub swap: Option<String>,
pub cpu: Option<String>,
pub maxproc: Option<u32>,
pub openfiles: Option<u32>,
pub cores: Option<u16>,
pub cpuset: Option<String>,
}
impl McpState {
#[mcp_tool(
name = "manifest_create",
description = "Render a blackship.toml from a project name and a list of jails, validate \
it with the same parser and semantic checks blackship itself uses, and \
write it only after the operator approves an elicitation. Returns the \
diagnostics and writes nothing when the rendered manifest is invalid, and \
never replaces an existing file unless the operator grants `overwrite`.",
destructive = true,
open_world = false
)]
async fn manifest_create(
&self,
ctx: Ctx<'_>,
params: Parameters<ManifestParams>,
) -> ToolResult {
let params = params.0;
let path = self.manifest_path(params.path.as_deref());
let rendered = render(¶ms)
.map_err(|e| ToolError::Execution(format!("Failed to render manifest: {e}")))?;
let report = super::manifest_validate::validate_text(
json!({
"path": path.display().to_string(),
"stages": ["parse", "validate"],
"rendered": rendered,
}),
&rendered,
);
if report["valid"] != json!(true) {
return json_output(&json!({
"written": false,
"reason": "The rendered manifest does not validate, so the operator was not \
asked. Fix the diagnostics and call this tool again.",
"validation": report,
}));
}
let outcome = elicit::write_with_approval(
&ctx,
&path,
&format!("a blackship.toml for project `{}`", params.project),
&rendered,
)
.await?;
let mut payload = outcome;
if let Some(object) = payload.as_object_mut() {
object.insert("rendered".to_string(), json!(rendered));
}
json_output(&payload)
}
}
pub(in crate::mcp) fn render(params: &ManifestParams) -> Result<String, toml::ser::Error> {
let mut root = Table::new();
root.insert("config".to_string(), TomlValue::Table(global_table(params)));
if !params.jails.is_empty() {
root.insert(
"jails".to_string(),
TomlValue::Array(params.jails.iter().map(jail_table).collect()),
);
}
toml::to_string_pretty(&root)
}
fn global_table(params: &ManifestParams) -> Table {
let mut table = Table::new();
table.insert(
"project".to_string(),
TomlValue::String(params.project.clone()),
);
insert_string(&mut table, "data_dir", params.data_dir.as_deref());
insert_string(&mut table, "releases_dir", params.releases_dir.as_deref());
if let Some(zpool) = ¶ms.zpool {
table.insert("zfs_enabled".to_string(), TomlValue::Boolean(true));
table.insert("zpool".to_string(), TomlValue::String(zpool.clone()));
insert_string(&mut table, "dataset", params.dataset.as_deref());
}
table
}
fn jail_table(jail: &JailParams) -> TomlValue {
let mut table = Table::new();
table.insert("name".to_string(), TomlValue::String(jail.name.clone()));
insert_string(&mut table, "release", jail.release.as_deref());
insert_string(&mut table, "path", jail.path.as_deref());
insert_string(&mut table, "build", jail.build.as_deref());
insert_string(&mut table, "jailfile", jail.jailfile.as_deref());
insert_string(&mut table, "hostname", jail.hostname.as_deref());
insert_string(&mut table, "stop", jail.stop.as_deref());
if let Some(init) = jail.init {
table.insert("init".to_string(), TomlValue::Boolean(init));
}
insert_strings(&mut table, "depends_on", &jail.depends_on);
insert_strings(&mut table, "tags", &jail.tags);
if !jail.params.is_empty() {
let params = jail
.params
.iter()
.map(|(key, value)| (key.clone(), param_value(value)))
.collect();
table.insert("params".to_string(), TomlValue::Table(params));
}
if let Some(network) = &jail.network {
table.insert(
"network".to_string(),
TomlValue::Table(network_table(network)),
);
}
if let Some(resources) = &jail.resources {
let resources = resource_table(resources);
if !resources.is_empty() {
table.insert("resources".to_string(), TomlValue::Table(resources));
}
}
TomlValue::Table(table)
}
fn network_table(network: &NetworkParams) -> Table {
let mut table = Table::new();
if network.vnet {
table.insert("vnet".to_string(), TomlValue::Boolean(true));
}
insert_string(&mut table, "bridge", network.bridge.as_deref());
insert_string(&mut table, "ip_cidr", network.ip_cidr.as_deref());
insert_string(&mut table, "ip", network.ip.as_deref());
insert_string(&mut table, "gateway", network.gateway.as_deref());
if !network.nameservers.is_empty() {
let mut dns = Table::new();
insert_strings(&mut dns, "nameservers", &network.nameservers);
dns.insert("mode".to_string(), TomlValue::String("custom".to_string()));
table.insert("dns".to_string(), TomlValue::Table(dns));
}
table
}
fn resource_table(resources: &ResourceParams) -> Table {
let mut table = Table::new();
insert_string(&mut table, "memory", resources.memory.as_deref());
insert_string(&mut table, "swap", resources.swap.as_deref());
insert_string(&mut table, "cpu", resources.cpu.as_deref());
insert_string(&mut table, "cpuset", resources.cpuset.as_deref());
if let Some(maxproc) = resources.maxproc {
table.insert("maxproc".to_string(), TomlValue::Integer(maxproc.into()));
}
if let Some(openfiles) = resources.openfiles {
table.insert("openfiles".to_string(), TomlValue::Integer(openfiles.into()));
}
if let Some(cores) = resources.cores {
table.insert("cores".to_string(), TomlValue::Integer(cores.into()));
}
table
}
fn param_value(value: &JailParamValue) -> TomlValue {
match value {
JailParamValue::Bool(flag) => TomlValue::Boolean(*flag),
JailParamValue::Integer(number) => TomlValue::Integer(*number),
JailParamValue::Text(text) => TomlValue::String(text.clone()),
}
}
fn insert_strings(table: &mut Table, key: &str, values: &[String]) {
if !values.is_empty() {
table.insert(
key.to_string(),
TomlValue::Array(
values
.iter()
.map(|value| TomlValue::String(value.clone()))
.collect(),
),
);
}
}
pub fn mount(router: McpToolRouter<McpState>) -> McpToolRouter<McpState> {
router.with_tool(
McpState::manifest_create_tool_info(),
McpState::manifest_create_handler,
None,
)
}
#[cfg(test)]
#[path = "manifest_create/tests.rs"]
mod tests;