use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use mcp_host::prelude::*;
use mcp_host::protocol::elicitation::ElicitationSchema;
use mcp_host::protocol::types::{CreateElicitationResult, ElicitationAction};
use serde_json::{Value, json};
const ANSWER_TIMEOUT: Duration = Duration::from_secs(120);
const NO_TRANSPORT: &str = "Client lacks the `elicitation` capability; approval impossible.";
#[derive(Debug, PartialEq, Eq)]
pub(in crate::mcp) enum Verdict {
Write { replacing: bool },
Refuse(String),
}
pub(in crate::mcp) async fn write_with_approval(
ctx: &Ctx<'_>,
path: &Path,
description: &str,
content: &str,
) -> std::result::Result<Value, ToolError> {
let target = absolute(path);
if let Some(parent) = missing_parent(&target) {
return Ok(refused(&target, &no_parent(&parent)));
}
let exists = target.exists();
let verdict = match ctx.client_requester() {
Some(requester) => ask(requester, &target, description, exists).await?,
None => Verdict::Refuse(NO_TRANSPORT.to_string()),
};
apply(&target, description, content, verdict)
}
async fn ask(
requester: &ClientRequester,
target: &Path,
description: &str,
exists: bool,
) -> std::result::Result<Verdict, ToolError> {
let schema = schema(description, exists)?;
let schema_value = serde_json::to_value(&schema)
.map_err(|e| ToolError::Execution(format!("Failed to encode elicitation schema: {e}")))?;
tracing::info!(
path = %target.display(),
target_exists = exists,
timeout_secs = ANSWER_TIMEOUT.as_secs(),
"asking the operator to approve a write"
);
let started = Instant::now();
let answer = requester
.request_elicitation(
message(target, description, exists),
schema_value,
Some(ANSWER_TIMEOUT),
)
.await;
let elapsed = started.elapsed();
let (outcome, verdict) = match answer {
Ok(result) => match verdict(&result, exists) {
write @ Verdict::Write { .. } => ("accepted-write", write),
refusal => ("refused-by-operator", refusal),
},
Err(MultiplexerError::Timeout(_)) => (
"timeout",
Verdict::Refuse(format!(
"No operator answer within {}s.",
ANSWER_TIMEOUT.as_secs()
)),
),
Err(MultiplexerError::UnsupportedCapability(_)) => (
"unsupported-capability",
Verdict::Refuse(NO_TRANSPORT.to_string()),
),
Err(e) => (
"other-error",
Verdict::Refuse(format!("Approval request failed: {e}")),
),
};
tracing::info!(
path = %target.display(),
outcome,
elapsed_secs = elapsed.as_secs_f64(),
"operator approval round-trip settled"
);
Ok(verdict)
}
fn schema(description: &str, exists: bool) -> std::result::Result<ElicitationSchema, ToolError> {
let mut builder = ElicitationSchema::builder()
.required_bool("confirm")
.title("blackship: approve file write")
.description(format!(
"Set `confirm` to write {description}. Leaving it unset writes nothing."
));
if exists {
builder = builder.optional_bool("overwrite", false);
}
builder
.build()
.map_err(|e| ToolError::Execution(format!("Schema error: {e}")))
}
fn message(target: &Path, description: &str, exists: bool) -> String {
let mut message = format!(
"blackship wants to write {description} to {}.",
target.display()
);
if exists {
message.push_str(
" A FILE ALREADY EXISTS AT THAT PATH and will be replaced. Set `overwrite` as well as \
`confirm` to allow that; `confirm` alone leaves the existing file untouched.",
);
} else {
message.push_str(" No file exists there yet.");
}
message.push_str(" Set `confirm` to approve. Nothing is written unless you do.");
message
}
fn verdict(result: &CreateElicitationResult, exists: bool) -> Verdict {
match result.action {
ElicitationAction::Decline => {
Verdict::Refuse("Operator declined. Do not retry.".to_string())
}
ElicitationAction::Cancel => Verdict::Refuse("Operator cancelled.".to_string()),
ElicitationAction::Accept if !flag(result.content.as_ref(), "confirm") => {
Verdict::Refuse("Form returned without `confirm`: not an approval.".to_string())
}
ElicitationAction::Accept if exists && !flag(result.content.as_ref(), "overwrite") => {
Verdict::Refuse("File exists; `overwrite` not granted.".to_string())
}
ElicitationAction::Accept => Verdict::Write { replacing: exists },
}
}
fn flag(content: Option<&Value>, key: &str) -> bool {
content
.and_then(|content| content.get(key))
.and_then(Value::as_bool)
== Some(true)
}
fn apply(
target: &Path,
description: &str,
content: &str,
verdict: Verdict,
) -> std::result::Result<Value, ToolError> {
let replacing = match verdict {
Verdict::Refuse(reason) => return Ok(refused(target, &reason)),
Verdict::Write { replacing } => replacing,
};
if !replacing && target.exists() {
return Ok(refused(
target,
"File appeared during approval; replacing it was not approved.",
));
}
crate::atomic::write_atomic(target, content, description)
.map_err(|e| ToolError::Execution(e.to_string()))?;
Ok(json!({
"path": target.display().to_string(),
"written": true,
"replaced": replacing,
"bytes": content.len(),
}))
}
fn refused(target: &Path, reason: &str) -> Value {
json!({
"path": target.display().to_string(),
"written": false,
"reason": reason,
})
}
fn no_parent(parent: &Path) -> String {
let shown = parent.display();
if parent.exists() {
format!("{shown} is not a directory; operator not asked.")
} else {
format!("{shown} does not exist; operator not asked. Blackship creates no directories.")
}
}
fn absolute(path: &Path) -> PathBuf {
std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf())
}
fn missing_parent(target: &Path) -> Option<PathBuf> {
let parent = target
.parent()
.filter(|parent| !parent.as_os_str().is_empty())?;
if parent.is_dir() {
None
} else {
Some(parent.to_path_buf())
}
}
#[cfg(test)]
#[path = "elicit/tests.rs"]
mod tests;