use crate::server::Pool;
use crate::stats::Stats;
use crate::types::Scheme;
use rmcp::schemars::{self, JsonSchema};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::sync::Arc;
#[derive(Debug, Serialize, JsonSchema)]
pub struct ProxyInfo {
pub proxy: String,
pub types: Vec<String>,
pub avg_resp_time: f64,
pub error_rate: f64,
}
#[derive(Debug, Serialize, JsonSchema)]
pub struct PoolStatus {
pub total: usize,
pub working: usize,
pub by_protocol: BTreeMap<String, usize>,
pub by_country: BTreeMap<String, usize>,
pub avg_resp_time: f64,
pub errors: BTreeMap<String, u32>,
}
#[derive(Debug, Serialize, JsonSchema)]
pub struct RemovedResult {
pub removed: bool,
}
#[derive(Debug, Deserialize, JsonSchema, Default)]
pub struct GetProxyParams {
pub scheme: String,
#[serde(default)]
pub country: Option<String>,
}
#[derive(Debug, Deserialize, JsonSchema, Default)]
pub struct ReportDeadParams {
pub proxy: String,
}
pub fn handle_get_proxy(pool: &Pool, scheme: Scheme, country: Option<&str>) -> Option<ProxyInfo> {
let proxy = pool.try_get(scheme, country)?;
let info = ProxyInfo {
proxy: proxy.addr(),
types: proxy
.types()
.keys()
.map(|p| p.as_str().to_string())
.collect(),
avg_resp_time: proxy.avg_resp_time(),
error_rate: proxy.error_rate(),
};
pool.add(proxy); Some(info)
}
pub fn handle_pool_status(pool: &Pool) -> PoolStatus {
let stats = Stats::from_proxies(&pool.proxies());
PoolStatus {
total: stats.total,
working: stats.working,
by_protocol: stats
.by_protocol
.iter()
.map(|(k, v)| (k.as_str().to_string(), *v))
.collect(),
by_country: stats.by_country.clone(),
avg_resp_time: stats.avg_resp_time,
errors: stats
.errors
.iter()
.map(|(k, v)| (k.to_string(), *v))
.collect(),
}
}
pub fn handle_report_dead(pool: &Pool, addr: &str) -> bool {
match addr.parse::<std::net::SocketAddr>() {
Ok(s) => pool.remove(s.ip(), s.port()),
Err(_) => false,
}
}
fn parse_scheme(s: &str) -> Option<Scheme> {
match s.to_ascii_lowercase().as_str() {
"http" => Some(Scheme::Http),
"https" => Some(Scheme::Https),
_ => None,
}
}
use rmcp::handler::server::wrapper::{Json, Parameters};
use rmcp::{tool, tool_router};
#[derive(Clone)]
pub struct ProxyTools {
pool: Arc<Pool>,
}
#[tool_router(server_handler)]
impl ProxyTools {
#[tool(
name = "get_proxy",
description = "Check out the best healthy proxy for a scheme (\"http\" or \"https\"), optionally filtered to an ISO country code. Returns its host:port and health metadata; the proxy stays in the pool. Null if none is available."
)]
fn get_proxy(&self, Parameters(p): Parameters<GetProxyParams>) -> Json<Option<ProxyInfo>> {
let info = parse_scheme(&p.scheme)
.and_then(|s| handle_get_proxy(&self.pool, s, p.country.as_deref()));
Json(info)
}
#[tool(
name = "pool_status",
description = "Snapshot of the live proxy pool: totals, per-protocol and per-country counts, mean latency, and the error histogram."
)]
fn pool_status(&self) -> Json<PoolStatus> {
Json(handle_pool_status(&self.pool))
}
#[tool(
name = "report_dead",
description = "Report a proxy (host:port) as dead so it is removed from the pool and no longer handed out."
)]
fn report_dead(&self, Parameters(p): Parameters<ReportDeadParams>) -> Json<RemovedResult> {
Json(RemovedResult {
removed: handle_report_dead(&self.pool, &p.proxy),
})
}
}
pub async fn serve_stdio(pool: Arc<Pool>) -> Result<(), Box<dyn std::error::Error>> {
use rmcp::ServiceExt;
let service = ProxyTools { pool }
.serve(rmcp::transport::io::stdio())
.await?;
service.waiting().await?;
Ok(())
}