use std::net::SocketAddr;
use std::sync::Arc;
use axum::Router;
use axum::routing::any_service;
use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
use super::ServerRuntime;
use super::auth::host_allow_list;
use crate::protocol::SymForgeServer;
use crate::sidecar::governor::RequestGovernor;
pub const MCP_PATH: &str = "/mcp";
#[cfg(feature = "server")]
async fn govern_mcp_concurrency(
axum::extract::State(governor): axum::extract::State<Arc<RequestGovernor>>,
request: axum::extract::Request,
next: axum::middleware::Next,
) -> axum::response::Response {
use axum::http::StatusCode;
use axum::response::IntoResponse;
match governor.acquire_request_slot().await {
Ok(_permit) => {
next.run(request).await
}
Err(_busy) => (
StatusCode::SERVICE_UNAVAILABLE,
[(axum::http::header::RETRY_AFTER, "1")],
"Service Unavailable: operator server at capacity, retry shortly",
)
.into_response(),
}
}
#[cfg(feature = "server")]
pub fn apply_governor(router: Router, governor: Arc<RequestGovernor>) -> Router {
router.layer(axum::middleware::from_fn_with_state(
governor,
govern_mcp_concurrency,
))
}
fn build_mcp_service(
runtime: &ServerRuntime,
bind_host: &str,
) -> StreamableHttpService<SymForgeServer, LocalSessionManager> {
let protocol = Arc::clone(runtime.protocol());
let service_factory = move || Ok((*protocol).clone());
let config = StreamableHttpServerConfig::default()
.with_legacy_session_mode(false)
.with_stateless_protocol_metadata_required(false)
.with_json_response(true)
.with_allowed_hosts(host_allow_list(bind_host));
StreamableHttpService::new(
service_factory,
Arc::new(LocalSessionManager::default()),
config,
)
}
pub fn build_mcp_router(runtime: &ServerRuntime, bind_addr: SocketAddr) -> Router {
let bind_host = bind_addr.ip().to_string();
let service = build_mcp_service(runtime, &bind_host);
let router = Router::new().route(MCP_PATH, any_service(service));
apply_governor(router, Arc::clone(runtime.governor()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn host_allow_list_keeps_loopback_defaults() {
let hosts = host_allow_list("127.0.0.1");
assert!(hosts.iter().any(|h| h == "localhost"));
assert!(hosts.iter().any(|h| h == "127.0.0.1"));
assert!(hosts.iter().any(|h| h == "::1"));
assert_eq!(
hosts.iter().filter(|h| h.as_str() == "127.0.0.1").count(),
1
);
}
#[test]
fn host_allow_list_adds_routable_bind_host() {
let hosts = host_allow_list("192.168.1.10");
assert!(hosts.iter().any(|h| h == "192.168.1.10"));
assert!(hosts.iter().any(|h| h == "localhost"));
}
#[test]
fn mcp_service_config_pins_the_sessionless_lane() {
use crate::live_index::LiveIndex;
use crate::server::AuthConfig;
use crate::watcher::WatcherInfo;
use parking_lot::Mutex;
let index = LiveIndex::empty();
let watcher_info = Arc::new(Mutex::new(WatcherInfo::default()));
let protocol = Arc::new(SymForgeServer::new(
Arc::clone(&index),
"mcp_http_config_pin".to_string(),
watcher_info,
None,
None,
));
let governor = Arc::new(RequestGovernor::new());
let runtime =
ServerRuntime::build_runtime(index, protocol, governor, AuthConfig::new(None), None);
let service = build_mcp_service(&runtime, "127.0.0.1");
assert!(
!service.config.legacy_session_mode,
"the /mcp lane must stay sessionless: the repeat tracker's HttpInert discriminator depends on it"
);
}
}