use std::env;
use std::io::{self, Write};
use std::path::PathBuf;
use clap::Args;
use super::rpc::serve;
use super::server::Server;
use crate::assets::{CONTEXT, literal};
use crate::cli::usage;
use crate::home::{project_mounts, user_mount};
use crate::memory::dispatch::Memory;
use crate::memory::grammar::{SCOPE_ENV, SUGAR_MOUNT_PATH};
use crate::memory::mounts::{Mount, Refusal};
use crate::record::context::{History, render_instructions_with};
use crate::remote::selection::Selection;
use crate::repr::repr;
use crate::state::records::HistoryReader;
use crate::store::grammar::Actor;
use crate::store::time::Stamp;
pub const DEFAULT_ACTOR: &str = "mcp:stdio";
const HOOKED_CLIENTS: [&str; 6] = ["claude-code", "codex", "cursor", "muse-code", "pi", "vibe"];
#[derive(Args)]
pub struct Mcp {
#[arg(long)]
profile: Option<String>,
#[arg(long)]
root: Option<PathBuf>,
#[arg(long)]
url: Option<String>,
#[arg(long)]
schema: Option<String>,
#[arg(long)]
scope: Option<String>,
#[arg(long, value_name = "scope=...,path=...[,ro|,eo]")]
mount: Vec<String>,
#[arg(long, default_value = DEFAULT_ACTOR)]
actor: String,
#[arg(long, hide = true)]
pinned: bool,
#[arg(long, hide = true, value_name = "SHA256", requires = "pinned")]
identity: Option<String>,
#[arg(long, hide = true)]
read_only: bool,
#[command(subcommand)]
command: Option<crate::clients::install::McpCommand>,
}
pub fn resolve_mounts(
scope: Option<&str>,
mount: &[String],
nameless: impl FnOnce() -> Result<Vec<Mount>, Refusal>,
) -> Result<Vec<Mount>, Refusal> {
if scope.is_some() && !mount.is_empty() {
let sugar = "--scope is the single-mount sugar; use --mount for multi-mount";
return Err(Refusal::Usage(sugar.to_string()));
}
if !mount.is_empty() {
let mounts: Vec<Mount> = mount
.iter()
.map(|token| Mount::parse(token))
.collect::<Result<_, _>>()?;
let twice = |mount: &Mount| {
mounts
.iter()
.filter(|other| other.path == mount.path)
.count()
> 1
};
if mounts.iter().any(twice) {
return Err(Refusal::Usage("mount paths must be unique".to_string()));
}
return Ok(mounts);
}
let named = env::var(SCOPE_ENV).ok().filter(|scope| !scope.is_empty());
if let Some(scope) = scope.or(named.as_deref()) {
return Ok(vec![Mount::new(
scope,
SUGAR_MOUNT_PATH,
(false, false),
"",
)?]);
}
let cwd = env::current_dir().map_err(|error| Refusal::Usage(error.to_string()))?;
match project_mounts(&cwd) {
Ok(mounts) => Ok(mounts),
Err(_) => nameless(),
}
}
fn hooked(actor: &str) -> bool {
let client = actor.strip_prefix("mcp:").unwrap_or("");
HOOKED_CLIENTS.contains(&client)
}
pub fn run(args: &Mcp, out: &mut impl Write, err: &mut impl Write) -> io::Result<u8> {
if let Some(crate::clients::install::McpCommand::Install(install)) = &args.command {
if args.profile.is_some() {
return usage(false, "place --profile after install", out, err);
}
return crate::clients::install::mcp(install, out, err);
}
let cwd = env::current_dir()?;
let resolve = || {
if args.pinned && args.profile.is_none() {
let (root, url) = (args.root.as_deref(), args.url.as_deref());
return Selection::resolve_schema(root, url, args.schema.as_deref());
}
Selection::resolve_profile(
args.root.as_deref(),
args.url.as_deref(),
args.schema.as_deref(),
args.profile.as_deref(),
&cwd,
args.scope.is_some() || !args.mount.is_empty(),
)
};
let selected = match resolve().and_then(|selection| {
if let Selection::Profile(profile) = &selection
&& profile.login.is_some()
&& crate::login::refresh_if_due(&profile.home)
{
return resolve();
}
Ok(selection)
}) {
Ok(selected) => selected,
Err(message) => return usage(false, &message, out, err),
};
#[cfg(unix)]
let expected = crate::harness::selection::expected(&selected, args.identity.as_deref());
#[cfg(not(unix))]
let expected = match args.identity {
Some(_) => Err("--identity names a harness child's selection, served on Unix only"),
None => Ok(()),
};
if let Err(message) = expected {
writeln!(err, "error: {message}")?;
return Ok(2);
}
let resolved_mounts = selected
.mounts()
.map(|m| m.map_err(Refusal::Usage))
.unwrap_or_else(|| {
resolve_mounts(args.scope.as_deref(), &args.mount, || {
Ok(vec![user_mount()?])
})
});
let mut mounts = match resolved_mounts {
Ok(mounts) => mounts,
Err(Refusal::Usage(message)) => return usage(false, &message, out, err),
Err(Refusal::Memory(error)) => {
writeln!(err, "error: [{}] {}", error.code, error.message)?;
return Ok(2);
}
};
if args.read_only {
for mount in &mut mounts {
(mount.read_only, mount.edit_only) = (true, false);
}
}
let actor = match Actor::parse(&args.actor) {
Ok(actor) => actor,
Err(reason) => {
let message = format!(
"--actor {}: {reason} (e.g. cli:claude-code)",
repr(&args.actor)
);
return usage(false, &message, out, err);
}
};
#[cfg(unix)]
let selection = crate::harness::selection::pin(&selected);
let history = match HistoryReader::open(&selected) {
Ok(history) => history,
Err(error) => {
writeln!(
err,
"error: {}",
crate::conversation::Error::from(error).text()
)?;
return Ok(1);
}
};
let store = history.state();
let instructions = if hooked(actor.as_str()) {
literal(
CONTEXT,
if store.profile().is_some() {
"profile_instructions"
} else {
"start_instructions"
},
)
.expect("context.yaml carries the discipline")
} else {
let rendered = history.records().and_then(|records| {
let records = records.as_deref();
match store.profile() {
Some(profile) if actor.as_str() == "mcp:opencode" => {
let limit = profile.context.max_chars
- crate::profile::context::opencode_hook_limit(profile);
let render = crate::profile::context::render_context;
render(store.as_ref(), records, &mounts, limit, None)
}
_ => {
let history = History::new(store.as_ref(), records);
render_instructions_with(history, &mounts, Stamp::now())
}
}
});
match rendered {
Ok(instructions) => instructions,
Err(error) => {
writeln!(err, "error: {}", error.text())?;
return Ok(1);
}
}
};
let memory = Memory {
store,
mounts,
actor,
};
let mut server = Server::new(memory, history, instructions);
#[cfg(unix)]
{
let mut warned = Vec::new();
let served = crate::harness::served(&mut |line: &str| warned.push(line.to_string()));
for line in warned {
writeln!(err, "{line}")?;
}
if let Some(settings) = served {
let registry = crate::harness::registry::Registry::new(settings, selection);
server = server.with_harness(registry);
}
}
if args.read_only {
server = server.read_only();
}
serve(&mut server, io::stdin().lock(), out)?;
Ok(0)
}