use crate::mcp::{McpServer, ServerInstance, get_registry};
use std::path::PathBuf;
use anyhow::Result;
use chrono::Local;
pub async fn run(
project_path: PathBuf,
port: u16,
bind: String,
watch: bool,
websocket: bool,
name: Option<String>,
allow_writes: bool,
) -> Result<()> {
let registry = get_registry();
if registry.is_port_in_use(port).await {
anyhow::bail!("Port {} is already in use by another RustF CLI instance", port);
}
if let Some(ref instance_name) = name {
if let Some(existing) = registry.find_by_name(instance_name).await {
anyhow::bail!(
"Instance named '{}' is already running on port {}",
instance_name,
existing.port
);
}
}
if websocket && registry.is_port_in_use(port + 1).await {
anyhow::bail!(
"Port {} is required for WebSocket but is already in use",
port + 1
);
}
let is_public_interface = bind != "127.0.0.1" && bind != "localhost";
if allow_writes && is_public_interface {
println!();
println!("⚠️ WARNING: Write operations enabled on public interface!");
println!("⚠️ Server will accept write commands from {}:{}", bind, port);
println!("⚠️ This could allow remote modification of your code!");
println!();
println!("For safe remote access, use read-only mode (default):");
println!(" rustf-cli serve --bind {}", bind);
println!();
println!("Press Ctrl+C to cancel, or wait 5 seconds to continue...");
tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
}
println!();
if allow_writes {
println!("🔓 Starting MCP Server with WRITE operations enabled");
println!(" Available: All CLI commands including generate, new, fix");
} else {
println!("🔒 Starting MCP Server in READ-ONLY mode (safe for remote)");
println!(" Available: analyze, query, validate, db list/describe");
println!(" Blocked: generate, new, fix, migrate");
println!(" To enable writes: --allow-writes (use with caution!)");
}
println!();
log::info!("Starting RustF MCP Server...");
if let Some(ref instance_name) = name {
log::info!("Instance name: {}", instance_name);
}
log::info!("Project: {}", project_path.display());
log::info!("Bind: {}:{}", bind, port);
log::info!("Mode: {}", if allow_writes { "read-write" } else { "read-only" });
log::info!("File watching: {}", if watch { "enabled" } else { "disabled" });
log::info!("WebSocket support: {}", if websocket { "enabled" } else { "disabled" });
let instance = ServerInstance::new(
name.clone(),
port,
bind.clone(),
project_path.clone(),
watch,
websocket,
);
registry.register(instance).await?;
let cleanup_port = port;
let cleanup_registry = get_registry();
let (shutdown_tx, mut shutdown_rx) = tokio::sync::mpsc::channel::<()>(1);
let shutdown_tx_clone = shutdown_tx.clone();
tokio::spawn(async move {
tokio::signal::ctrl_c().await.expect("Failed to listen for Ctrl+C");
let _ = shutdown_tx_clone.send(()).await;
});
let read_only = !allow_writes; let server = McpServer::new(project_path, watch, read_only)?;
let server_task = tokio::spawn(async move {
if websocket {
log::info!("Starting MCP server with WebSocket support on {}:{}", bind, port);
server.start_with_websocket(&bind, port).await
} else {
log::info!("Starting MCP server (HTTP only) on {}:{}", bind, port);
server.start(&bind, port).await
}
});
tokio::select! {
result = server_task => {
cleanup_registry.unregister(cleanup_port).await?;
result??
}
_ = shutdown_rx.recv() => {
log::info!("Shutting down server...");
cleanup_registry.unregister(cleanup_port).await?;
}
}
Ok(())
}
pub async fn find_available_port(start_port: u16) -> Option<u16> {
let registry = get_registry();
registry.find_available_port(start_port, 100).await
}
pub async fn list() -> Result<()> {
let registry = get_registry();
let instances = registry.list_instances().await;
if instances.is_empty() {
println!("No RustF MCP servers are currently running.");
return Ok(());
}
println!("🚀 Running RustF MCP Server Instances:\n");
println!("{:<20} {:<10} {:<15} {:<10} {:<10} {:<30} {:<20}",
"Name", "Port", "Bind", "PID", "WebSocket", "Project", "Started");
println!("{}", "-".repeat(125));
for instance in instances {
let name = instance.name.as_deref().unwrap_or("(unnamed)");
let ws_info = if instance.websocket_enabled {
format!("Yes ({})", instance.websocket_port.unwrap_or(0))
} else {
"No".to_string()
};
let started = instance.started_at.with_timezone(&Local).format("%Y-%m-%d %H:%M:%S");
println!("{:<20} {:<10} {:<15} {:<10} {:<10} {:<30} {:<20}",
name,
instance.port,
instance.bind_address,
instance.pid,
ws_info,
instance.project_path.display(),
started
);
}
println!("\n💡 Use 'rustf-cli serve-stop <port>' to stop a server instance.");
Ok(())
}
pub async fn stop(port: u16) -> Result<()> {
let registry = get_registry();
match registry.get_instance(port).await {
Some(instance) => {
#[cfg(unix)]
{
use std::process::Command;
let pid = instance.pid;
match Command::new("kill")
.arg("-TERM")
.arg(pid.to_string())
.output()
{
Ok(output) => {
if output.status.success() {
println!("✅ Sent shutdown signal to server on port {} (PID: {})", port, pid);
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
if !instance.is_alive() {
println!("✅ Server stopped successfully.");
} else {
let _ = Command::new("kill")
.arg("-KILL")
.arg(pid.to_string())
.output();
println!("⚠️ Server was forcefully terminated.");
}
registry.unregister(port).await?;
} else {
anyhow::bail!("Failed to stop server: {}", String::from_utf8_lossy(&output.stderr));
}
}
Err(e) => {
anyhow::bail!("Failed to stop server: {}", e);
}
}
}
#[cfg(windows)]
{
use std::process::Command;
let pid = instance.pid;
match Command::new("taskkill")
.args(&["/PID", &pid.to_string(), "/F"])
.output()
{
Ok(output) => {
if output.status.success() {
println!("✅ Server on port {} (PID: {}) stopped successfully.", port, pid);
registry.unregister(port).await?;
} else {
anyhow::bail!("Failed to stop server: {}", String::from_utf8_lossy(&output.stderr));
}
}
Err(e) => {
anyhow::bail!("Failed to stop server: {}", e);
}
}
}
#[cfg(not(any(unix, windows)))]
{
anyhow::bail!("Stopping servers is not supported on this platform");
}
}
None => {
if registry.is_port_in_use(port).await {
registry.unregister(port).await?;
println!("✅ Removed stale server entry for port {}", port);
} else {
anyhow::bail!("No server found running on port {}", port);
}
}
}
Ok(())
}