use std::process::ExitCode;
use pikopiko::lang::Arg;
use pikopiko_cli::args::{mcp_command, McpCli};
use pikopiko_cli::mcp::{serve_stdio, Config};
use pikopiko_cli::text::Texts;
fn main() -> ExitCode {
let (cli, texts) = pikopiko_cli::args::parse::<McpCli>(mcp_command);
let http = match http_options(&cli, &texts) {
Ok(h) => h,
Err(msg) => {
eprintln!("pikopiko-mcp: {msg}");
return ExitCode::from(2);
}
};
let config = match config(cli, &texts) {
Ok(c) => c,
Err(msg) => {
eprintln!("pikopiko-mcp: {msg}");
return ExitCode::from(2);
}
};
let result = match http {
None => tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(Into::into)
.and_then(|rt| rt.block_on(serve_stdio(config))),
#[cfg(feature = "mcp-http")]
Some(opts) => run_http(config, opts, &texts),
#[cfg(not(feature = "mcp-http"))]
Some(never) => match never {},
};
if let Err(e) = result {
eprintln!(
"pikopiko-mcp: {}",
texts.tr_args(
"mcp-err-serve",
&[("error", serve_error(&texts, &*e).into())]
)
);
return ExitCode::from(1);
}
ExitCode::SUCCESS
}
#[cfg(not(feature = "mcp-http"))]
enum Never {}
#[cfg(not(feature = "mcp-http"))]
type HttpParams = Never;
#[cfg(feature = "mcp-http")]
type HttpParams = pikopiko_cli::mcp::http::HttpOptions;
fn http_options(cli: &McpCli, texts: &Texts) -> Result<Option<HttpParams>, String> {
let Some(addr) = &cli.http else {
return Ok(None);
};
#[cfg(not(feature = "mcp-http"))]
{
let _ = addr;
Err(texts.tr("mcp-err-http-unavailable"))
}
#[cfg(feature = "mcp-http")]
{
use pikopiko_cli::mcp::http::{HttpOptions, HttpOptionsError, DEFAULT_MAX_CONCURRENCY};
let addr_value = Arg::from(addr.as_str());
let sock: std::net::SocketAddr = addr.parse().map_err(|_| {
texts.tr_args("mcp-err-bad-http-addr", &[("value", addr_value.clone())])
})?;
let max_concurrency = match &cli.max_concurrency {
None => DEFAULT_MAX_CONCURRENCY,
Some(v) => v.parse::<usize>().ok().filter(|&n| n >= 1).ok_or_else(|| {
texts.tr_args(
"mcp-err-bad-concurrency",
&[("value", Arg::from(v.as_str()))],
)
})?,
};
let token = cli
.token
.clone()
.or_else(|| std::env::var("PIKOPIKO_MCP_TOKEN").ok());
let opts = HttpOptions {
addr: sock,
token,
allowed_hosts: cli.allow_host.clone(),
max_concurrency,
};
opts.validate().map_err(|e| match e {
HttpOptionsError::TokenRequired => {
texts.tr_args("mcp-err-http-token-required", &[("addr", addr_value)])
}
HttpOptionsError::EmptyToken => texts.tr("mcp-err-http-empty-token"),
HttpOptionsError::BadConcurrency => texts.tr_args(
"mcp-err-bad-concurrency",
&[("value", Arg::from(max_concurrency.to_string().as_str()))],
),
})?;
Ok(Some(opts))
}
}
#[cfg(feature = "mcp-http")]
fn run_http(
config: Config,
opts: HttpParams,
texts: &Texts,
) -> Result<(), Box<dyn std::error::Error>> {
use pikopiko_cli::mcp::http::HttpServer;
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(opts.max_concurrency.max(2))
.enable_all()
.build()?;
rt.block_on(async {
let server = HttpServer::bind(opts).await?;
let addr = server.local_addr()?.to_string();
eprintln!(
"pikopiko-mcp: {}",
texts.tr_args("mcp-http-listening", &[("addr", Arg::from(addr.as_str()))])
);
server
.serve(config, async {
let _ = tokio::signal::ctrl_c().await;
})
.await?;
Ok(())
})
}
fn config(cli: McpCli, texts: &Texts) -> Result<Config, String> {
let mut config = Config {
lang: texts.lang(),
..Config::default()
};
if let Some(dir) = cli.out_dir {
config.out_dir = dir;
}
config.ref_dir = cli
.ref_dir
.or_else(|| std::env::var_os("PIKOPIKO_MCP_REF_DIR").map(std::path::PathBuf::from))
.filter(|d| !d.as_os_str().is_empty());
if let Some(v) = cli.max_seconds {
config.max_render_secs = v
.parse::<f64>()
.ok()
.filter(|s| s.is_finite() && *s > 0.0)
.ok_or_else(|| {
texts.tr_args("mcp-err-bad-seconds", &[("value", Arg::from(v.as_str()))])
})?;
}
if let Some(v) = cli.max_inline {
config.max_inline = pikopiko_cli::inline::parse_size(&v)
.filter(|&n| n > 0)
.ok_or_else(|| {
texts.tr_args("mcp-err-bad-inline", &[("value", Arg::from(v.as_str()))])
})?;
}
let synths_env = std::env::var_os("PIKOPIKO_SYNTHS");
pikopiko_cli::synthdefs::register_all(&cli.synth_def, synths_env.as_deref()).map_err(|e| {
let (key, vals) = e.parts(|io| texts.io_error(io));
let args: Vec<(&str, Arg)> = vals
.iter()
.map(|(k, v)| (*k, Arg::from(v.as_str())))
.collect();
texts.tr_args(&format!("mcp-err-synthdef-{key}"), &args)
})?;
let env = std::env::var_os("PIKOPIKO_TONES");
config.tones = pikopiko_cli::tones::load_all(&cli.tones, env.as_deref()).map_err(|e| {
use pikopiko_cli::tones::TonesError;
match e {
TonesError::Read(p, e) => texts.tr_args(
"mcp-err-tones-read",
&[
("path", Arg::from(p.display().to_string().as_str())),
("error", Arg::from(texts.io_error(&e).as_str())),
],
),
TonesError::BadToml(p) => texts.tr_args(
"mcp-err-tones-toml",
&[("path", Arg::from(p.display().to_string().as_str()))],
),
TonesError::Field(p, f) => texts.tr_args(
"mcp-err-tones-field",
&[
("path", Arg::from(p.display().to_string().as_str())),
("field", Arg::from(f)),
],
),
TonesError::BadName(p, n) => texts.tr_args(
"mcp-err-tones-name",
&[
("path", Arg::from(p.display().to_string().as_str())),
("name", Arg::from(n.as_str())),
],
),
}
})?;
Ok(config)
}
fn serve_error(texts: &Texts, e: &(dyn std::error::Error + 'static)) -> String {
match e.downcast_ref::<std::io::Error>() {
Some(io) => texts.io_error(io),
None => e.to_string(),
}
}