use std::str::FromStr;
use axum::{extract::Request, http::StatusCode, middleware::Next, response::Response};
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use tracing::debug;
use crate::model::{McpConfig, McpRouterPath, McpType};
pub(crate) async fn mcp_json_config_extract(
mut req: Request,
next: Next,
) -> Result<Response, StatusCode> {
let path = req.uri().path().to_string();
debug!("Request path: {path}");
let check_mcp_path = McpRouterPath::check_mcp_path(&path);
if check_mcp_path {
let mcp_router_path = McpRouterPath::from_url(&path);
if let Some(mcp_router_path) = mcp_router_path {
let mcp_id = mcp_router_path.mcp_id.clone();
let mcp_json_config = req
.headers()
.get("x-mcp-json")
.and_then(|value| value.to_str().ok())
.and_then(|encoded| {
let decoded = BASE64
.decode(encoded)
.ok()
.and_then(|bytes| String::from_utf8(bytes).ok());
debug!("Parsed MCP configuration, x-mcp-json={:?}", &decoded);
decoded
});
let mcp_type = req
.headers()
.get("x-mcp-type")
.and_then(|value| value.to_str().ok())
.and_then(|s| McpType::from_str(s).ok())
.unwrap_or_default();
let mcp_protocol = mcp_router_path.mcp_protocol.clone();
let mcp_config = McpConfig::new(mcp_id, mcp_json_config, mcp_type, mcp_protocol);
req.extensions_mut().insert(mcp_config);
}
}
Ok(next.run(req).await)
}