use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::io::{self, BufRead, Write};
use std::path::Path;
use std::sync::Arc;
use anyhow::Result;
use clap::Parser;
use is_terminal::IsTerminal;
use tokio::sync::Mutex;
use axum::{
extract::State,
response::{IntoResponse, Response},
routing::post,
Json, Router,
};
use tower_http::cors::CorsLayer;
use poly_mcp::config::{all_module_info, is_module_compiled};
use poly_mcp::{PolyMcp, ToolConfig};
#[derive(Parser, Debug)]
#[command(name = "poly-mcp")]
#[command(version = env!("CARGO_PKG_VERSION"))]
#[command(about = "A comprehensive MCP server with configurable modules", long_about = None)]
struct Cli {
#[arg(short, long)]
list_modules: bool,
#[arg(short, long)]
verbose: bool,
#[arg(short, long)]
server: bool,
#[arg(short, long, default_value = "3000")]
port: u16,
#[arg(long, default_value = "127.0.0.1")]
host: String,
#[arg(short, long, value_name = "MODULES")]
modules: Option<String>,
#[arg(long, value_name = "MODULES")]
disable_modules: Option<String>,
#[arg(long, value_name = "TOOLS")]
disable_tools: Option<String>,
#[arg(short, long, value_name = "PATH")]
config: Option<String>,
#[arg(long)]
generate_config: bool,
}
#[derive(Debug, Serialize, Deserialize)]
struct JsonRpcRequest {
jsonrpc: String,
id: Option<Value>,
method: String,
params: Option<Value>,
}
#[derive(Debug, Serialize, Deserialize)]
struct JsonRpcResponse {
jsonrpc: String,
id: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
result: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<JsonRpcError>,
}
#[derive(Debug, Serialize, Deserialize)]
struct JsonRpcError {
code: i32,
message: String,
#[serde(skip_serializing_if = "Option::is_none")]
data: Option<Value>,
}
async fn handle_mcp_request(server: &mut PolyMcp, request: JsonRpcRequest) -> JsonRpcResponse {
let id = request.id.clone();
match request.method.as_str() {
"initialize" => JsonRpcResponse {
jsonrpc: "2.0".to_string(),
id,
result: Some(server.get_server_info()),
error: None,
},
"tools/list" => JsonRpcResponse {
jsonrpc: "2.0".to_string(),
id,
result: Some(server.list_tools()),
error: None,
},
"tools/call" => {
let params = request.params.unwrap_or(json!({}));
let name = params["name"].as_str().unwrap_or("");
let arguments = params.get("arguments").cloned();
match server.call_tool(name, arguments).await {
Ok(result) => {
let response_content = if result
.get("content")
.and_then(|c| c.as_array())
.is_some()
{
result
} else {
json!({
"content": [{
"type": "text",
"text": result.to_string()
}]
})
};
JsonRpcResponse {
jsonrpc: "2.0".to_string(),
id,
result: Some(response_content),
error: None,
}
}
Err(e) => JsonRpcResponse {
jsonrpc: "2.0".to_string(),
id,
result: None,
error: Some(JsonRpcError {
code: -32000,
message: e.to_string(),
data: None,
}),
},
}
}
_ => JsonRpcResponse {
jsonrpc: "2.0".to_string(),
id,
result: None,
error: Some(JsonRpcError {
code: -32601,
message: format!("Method not found: {}", request.method),
data: None,
}),
},
}
}
fn print_banner(server: &PolyMcp, verbose: bool) {
let active = server.active_module_count();
eprintln!("\n╭────────────────────────────────────────────────────╮");
eprintln!("│ 🔧 Poly MCP Server v{} │", env!("CARGO_PKG_VERSION"));
eprintln!("╰────────────────────────────────────────────────────╯\n");
eprintln!("📡 Protocol: Model Context Protocol (MCP)");
eprintln!("🔗 Transport: stdio (stdin/stdout) - no network port");
eprintln!("📋 Format: JSON-RPC 2.0");
eprintln!("📦 Modules: {} active module(s) loaded\n", active);
if verbose {
print_module_status(server);
}
eprintln!("✓ Server ready and listening for JSON-RPC requests...");
eprintln!("ℹ Use --help for more information\n");
}
fn print_module_status(server: &PolyMcp) {
eprintln!("Module Status:");
for info in all_module_info() {
let compiled = is_module_compiled(info.name);
let runtime_enabled = server.config().modules.is_enabled(info.name);
let (icon, status) = if !compiled {
("○", "NOT COMPILED")
} else if !runtime_enabled {
("✗", "DISABLED")
} else {
("✓", "ACTIVE")
};
eprintln!(
" {} {:12} - {:3} tools [{}]",
icon, info.name, info.tool_count, status
);
}
eprintln!();
let cfg = server.config();
if !cfg.tools.enabled.is_empty() {
eprintln!(
"Tool whitelist: {} tool(s) explicitly enabled",
cfg.tools.enabled.len()
);
}
if !cfg.tools.disabled.is_empty() {
eprintln!(
"Tool blacklist: {} tool(s) disabled: {}",
cfg.tools.disabled.len(),
cfg.tools.disabled.join(", ")
);
}
if !cfg.tools.enabled.is_empty() || !cfg.tools.disabled.is_empty() {
eprintln!();
}
}
fn list_all_modules(server: &PolyMcp) {
println!("\n╭────────────────────────────────────────────────────╮");
println!("│ 🔧 Poly MCP - Available Modules │");
println!("╰────────────────────────────────────────────────────╯\n");
let mut total_active = 0;
let mut total_tools = 0;
for info in all_module_info() {
let compiled = is_module_compiled(info.name);
let runtime_enabled = server.config().modules.is_enabled(info.name);
let (icon, status) = if !compiled {
("⬜", "NOT COMPILED")
} else if !runtime_enabled {
("🚫", "DISABLED")
} else {
("📦", "ACTIVE")
};
println!("{} {} - {} [{}]", icon, info.name, info.description, status);
println!(" {} tools: {}", info.tool_count, info.tools.join(", "));
println!();
if compiled && runtime_enabled {
total_active += 1;
total_tools += info.tool_count;
}
}
println!(
"Active: {}/{} modules, {} tools\n",
total_active,
all_module_info().len(),
total_tools
);
}
fn build_config(cli: &Cli) -> Result<ToolConfig> {
let mut config = ToolConfig::default();
let config_path = cli.config.as_deref().or_else(|| {
let auto_path = "poly-mcp.config.json";
if Path::new(auto_path).exists() {
Some(auto_path)
} else {
None
}
});
if let Some(path) = config_path {
match ToolConfig::from_file(Path::new(path)) {
Ok(file_config) => {
config = file_config;
eprintln!("📄 Loaded config from: {}", path);
}
Err(e) => {
if cli.config.is_some() {
return Err(anyhow::anyhow!("Failed to load config '{}': {}", path, e));
} else {
eprintln!("⚠ Failed to parse poly-mcp.config.json: {}", e);
}
}
}
}
config.apply_cli(
cli.modules.as_deref(),
cli.disable_modules.as_deref(),
cli.disable_tools.as_deref(),
);
Ok(config)
}
type SharedState = Arc<Mutex<PolyMcp>>;
async fn handle_jsonrpc(
State(state): State<SharedState>,
Json(request): Json<JsonRpcRequest>,
) -> Response {
let mut server = state.lock().await;
let response = handle_mcp_request(&mut server, request).await;
Json(response).into_response()
}
async fn health_check() -> Response {
Json(json!({
"status": "healthy",
"service": "poly-mcp",
"version": env!("CARGO_PKG_VERSION")
}))
.into_response()
}
async fn run_http_mode(cli: &Cli, config: ToolConfig) -> Result<()> {
let server = PolyMcp::new(config);
let active = server.active_module_count();
let state = Arc::new(Mutex::new(server));
let app = Router::new()
.route("/", post(handle_jsonrpc))
.route("/jsonrpc", post(handle_jsonrpc))
.route("/health", axum::routing::get(health_check))
.layer(CorsLayer::permissive())
.with_state(state.clone());
let addr = format!("{}:{}", cli.host, cli.port);
let listener = tokio::net::TcpListener::bind(&addr).await?;
eprintln!("\n╭────────────────────────────────────────────────────╮");
eprintln!("│ 🔧 Poly MCP Server v{} │", env!("CARGO_PKG_VERSION"));
eprintln!("╰────────────────────────────────────────────────────╯\n");
eprintln!("📡 Protocol: Model Context Protocol (MCP)");
eprintln!("🔗 Transport: HTTP (JSON-RPC 2.0)");
eprintln!("🌐 Address: http://{}", addr);
eprintln!("📦 Modules: {} active module(s) loaded", active);
eprintln!("💚 Health: http://{}/health\n", addr);
if cli.verbose {
let server = state.lock().await;
print_module_status(&server);
}
eprintln!("✓ Server ready and listening for HTTP requests...");
eprintln!("ℹ Press Ctrl+C to stop\n");
axum::serve(listener, app).await?;
Ok(())
}
async fn run_stdio_mode(cli: &Cli, config: ToolConfig) -> Result<()> {
let mut server = PolyMcp::new(config);
if io::stdin().is_terminal() {
print_banner(&server, cli.verbose);
}
let stdin = io::stdin();
let mut stdout = io::stdout();
for line in stdin.lock().lines() {
let line = line?;
if line.trim().is_empty() {
continue;
}
match serde_json::from_str::<JsonRpcRequest>(&line) {
Ok(request) => {
let response = handle_mcp_request(&mut server, request).await;
let response_json = serde_json::to_string(&response)?;
writeln!(stdout, "{}", response_json)?;
stdout.flush()?;
}
Err(e) => {
let error_response = JsonRpcResponse {
jsonrpc: "2.0".to_string(),
id: None,
result: None,
error: Some(JsonRpcError {
code: -32700,
message: format!("Parse error: {}", e),
data: None,
}),
};
let response_json = serde_json::to_string(&error_response)?;
writeln!(stdout, "{}", response_json)?;
stdout.flush()?;
}
}
}
Ok(())
}
#[tokio::main]
async fn main() -> Result<()> {
let cli = Cli::parse();
tracing_subscriber::fmt::init();
if cli.generate_config {
println!("{}", ToolConfig::generate_default());
return Ok(());
}
let config = build_config(&cli)?;
if cli.list_modules {
let server = PolyMcp::new(config);
list_all_modules(&server);
return Ok(());
}
if cli.server {
run_http_mode(&cli, config).await
} else {
run_stdio_mode(&cli, config).await
}
}