use crate::agent::ToolAudience;
use crate::mcp::registry;
use serde_json::Value;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, LazyLock, RwLock};
use tokio::sync::Mutex;
use tokio::time::Instant;
#[doc(hidden)]
pub struct RequestGuard {
active: ActiveRequests,
request_id: Value,
}
impl RequestGuard {
#[doc(hidden)]
pub fn new(active: ActiveRequests, _cancel_flag: &Arc<AtomicBool>, request_id: Value) -> Self {
Self { active, request_id }
}
}
impl Drop for RequestGuard {
fn drop(&mut self) {
#[cfg(debug_assertions)]
{
if let Ok(map) = self.active.try_lock() {
debug_assert!(
!map.contains_key(&self.request_id),
"RequestGuard dropped but entry still active for {:?}",
self.request_id
);
}
}
}
}
#[doc(hidden)]
pub const MAX_IN_FLIGHT_REQUESTS: usize = 32;
#[doc(hidden)]
pub const MAX_TOOL_WORKERS: usize = 16;
#[doc(hidden)]
pub const MAX_REQUEST_ID_LENGTH: usize = 1024;
#[doc(hidden)]
pub const MAX_REQUEST_BYTES: usize = 1_000_000;
#[doc(hidden)]
pub const MAX_OUTPUT_BYTES: usize = 1_000_000;
pub(crate) const SCHEMA_DETAIL_FULL: &str = "full";
pub const MCP_SERVER_NAME: &str = "eggsact";
pub const SUPPORTED_PROTOCOL_VERSIONS: &[&str] = &["2025-11-25", "2024-11-05"];
pub const PREFERRED_PROTOCOL_VERSION: &str = SUPPORTED_PROTOCOL_VERSIONS[0];
pub const MCP_PROTOCOL_VERSION: &str = PREFERRED_PROTOCOL_VERSION;
pub fn is_supported_protocol_version(version: &str) -> bool {
SUPPORTED_PROTOCOL_VERSIONS.contains(&version)
}
pub fn negotiate_protocol_version(requested: &str) -> String {
if is_supported_protocol_version(requested) {
requested.to_string()
} else {
PREFERRED_PROTOCOL_VERSION.to_string()
}
}
#[derive(Debug, Clone)]
pub struct NegotiatedProtocol {
pub version: String,
pub client_name: String,
pub client_version: Option<String>,
pub client_capabilities: crate::mcp::protocol::ClientCapabilities,
}
impl NegotiatedProtocol {
pub fn supports_initialized_notification(&self) -> bool {
true
}
pub fn allows_extension_capabilities(&self) -> bool {
true
}
pub fn client_capabilities(&self) -> &crate::mcp::protocol::ClientCapabilities {
&self.client_capabilities
}
}
#[derive(Debug, Clone)]
pub enum SessionState {
Uninitialized,
AwaitingInitialized { negotiated: NegotiatedProtocol },
Ready { negotiated: NegotiatedProtocol },
}
impl SessionState {
pub fn allows_method(&self, method: &str) -> bool {
match (self, method) {
(SessionState::Uninitialized, "initialize") => true,
(SessionState::Uninitialized, "ping") => true,
(SessionState::Uninitialized, _) => false,
(SessionState::AwaitingInitialized { .. }, "notifications/initialized") => true,
(SessionState::AwaitingInitialized { .. }, "ping") => true,
(SessionState::AwaitingInitialized { .. }, _) => false,
(SessionState::Ready { .. }, "initialize") => false,
(SessionState::Ready { .. }, _) => true,
}
}
pub fn transition_to_awaiting(
&mut self,
negotiated: NegotiatedProtocol,
) -> Result<(), &'static str> {
match self {
SessionState::Uninitialized => {
*self = SessionState::AwaitingInitialized { negotiated };
Ok(())
}
_ => Err("already_initialized"),
}
}
pub fn transition_to_ready(&mut self) -> Result<(), &'static str> {
match self {
SessionState::AwaitingInitialized { negotiated } => {
let negotiated = negotiated.clone();
*self = SessionState::Ready { negotiated };
Ok(())
}
_ => Err("not_awaiting_initialized"),
}
}
pub fn negotiated(&self) -> Option<&NegotiatedProtocol> {
match self {
SessionState::Uninitialized => None,
SessionState::AwaitingInitialized { negotiated } => Some(negotiated),
SessionState::Ready { negotiated } => Some(negotiated),
}
}
}
#[cfg(test)]
mod lifecycle_tests {
use super::*;
#[test]
fn uninitialized_allows_only_initialize_and_ping() {
let state = SessionState::Uninitialized;
assert!(state.allows_method("initialize"));
assert!(state.allows_method("ping"));
assert!(!state.allows_method("tools/list"));
assert!(!state.allows_method("tools/call"));
assert!(!state.allows_method("profiles/list"));
assert!(!state.allows_method("notifications/initialized"));
}
#[test]
fn awaiting_initialized_allows_only_notification_and_ping() {
let negotiated = NegotiatedProtocol {
version: "2024-11-05".to_string(),
client_name: "test".to_string(),
client_version: None,
client_capabilities: crate::mcp::protocol::ClientCapabilities::default(),
};
let state = SessionState::AwaitingInitialized {
negotiated: negotiated.clone(),
};
assert!(state.allows_method("notifications/initialized"));
assert!(state.allows_method("ping"));
assert!(!state.allows_method("initialize"));
assert!(!state.allows_method("tools/list"));
assert!(!state.allows_method("tools/call"));
}
#[test]
fn ready_allows_all_except_initialize() {
let negotiated = NegotiatedProtocol {
version: "2024-11-05".to_string(),
client_name: "test".to_string(),
client_version: None,
client_capabilities: crate::mcp::protocol::ClientCapabilities::default(),
};
let state = SessionState::Ready { negotiated };
assert!(!state.allows_method("initialize"));
assert!(state.allows_method("tools/list"));
assert!(state.allows_method("tools/call"));
assert!(state.allows_method("profiles/list"));
assert!(state.allows_method("ping"));
assert!(state.allows_method("some_extension"));
}
#[test]
fn transition_to_awaiting_from_uninitialized() {
let negotiated = NegotiatedProtocol {
version: "2024-11-05".to_string(),
client_name: "test".to_string(),
client_version: None,
client_capabilities: crate::mcp::protocol::ClientCapabilities::default(),
};
let mut state = SessionState::Uninitialized;
assert!(state.transition_to_awaiting(negotiated).is_ok());
assert!(matches!(state, SessionState::AwaitingInitialized { .. }));
}
#[test]
fn transition_to_awaiting_from_non_uninitialized_fails() {
let negotiated = NegotiatedProtocol {
version: "2024-11-05".to_string(),
client_name: "test".to_string(),
client_version: None,
client_capabilities: crate::mcp::protocol::ClientCapabilities::default(),
};
let mut state = SessionState::AwaitingInitialized {
negotiated: negotiated.clone(),
};
assert_eq!(
state.transition_to_awaiting(negotiated).unwrap_err(),
"already_initialized"
);
}
#[test]
fn transition_to_ready_from_awaiting() {
let negotiated = NegotiatedProtocol {
version: "2024-11-05".to_string(),
client_name: "test".to_string(),
client_version: None,
client_capabilities: crate::mcp::protocol::ClientCapabilities::default(),
};
let mut state = SessionState::AwaitingInitialized { negotiated };
assert!(state.transition_to_ready().is_ok());
assert!(matches!(state, SessionState::Ready { .. }));
}
#[test]
fn transition_to_ready_from_wrong_state_fails() {
let mut state = SessionState::Uninitialized;
assert_eq!(
state.transition_to_ready().unwrap_err(),
"not_awaiting_initialized"
);
}
#[test]
fn negotiated_version_persists_through_transitions() {
let negotiated = NegotiatedProtocol {
version: "2025-11-25".to_string(),
client_name: "my-client".to_string(),
client_version: Some("2.0".to_string()),
client_capabilities: crate::mcp::protocol::ClientCapabilities::default(),
};
let mut state = SessionState::Uninitialized;
state.transition_to_awaiting(negotiated).unwrap();
assert_eq!(
state.negotiated().map(|n| n.version.as_str()),
Some("2025-11-25")
);
state.transition_to_ready().unwrap();
assert_eq!(
state.negotiated().map(|n| n.version.as_str()),
Some("2025-11-25")
);
assert_eq!(
state.negotiated().and_then(|n| n.client_version.as_deref()),
Some("2.0")
);
}
}
static ACTIVE_PROFILE: LazyLock<RwLock<String>> = LazyLock::new(|| {
let profile = std::env::var("EGGCALC_MCP_PROFILE").unwrap_or_else(|_| "full".to_string());
RwLock::new(if registry::PROFILE_NAMES.contains(&profile.as_str()) {
profile
} else {
"full".to_string()
})
});
pub fn init_active_profile() -> Result<(), String> {
let profile = std::env::var("EGGCALC_MCP_PROFILE").unwrap_or_else(|_| "full".to_string());
if !registry::PROFILE_NAMES.contains(&profile.as_str()) {
let available: Vec<&str> = registry::PROFILE_NAMES.to_vec();
return Err(format!(
"Invalid EGGCALC_MCP_PROFILE: {:?}. Available profiles: {}",
profile,
available.join(", ")
));
}
set_active_profile(&profile)
}
#[doc(hidden)]
pub fn parse_schema_detail(s: &str) -> Option<&'static str> {
match s {
"compact" => Some("compact"),
"normal" => Some("normal"),
"full" => Some("full"),
_ => None,
}
}
static ACTIVE_SCHEMA_DETAIL: LazyLock<RwLock<String>> = LazyLock::new(|| {
let raw = std::env::var("EGGCALC_MCP_SCHEMA_DETAIL")
.unwrap_or_else(|_| SCHEMA_DETAIL_FULL.to_string());
match parse_schema_detail(&raw) {
Some(valid) => RwLock::new(valid.to_string()),
None => {
eprintln!(
"Warning: Invalid EGGCALC_MCP_SCHEMA_DETAIL: {:?}. \
Accepted values: compact, normal, full. Defaulting to full.",
raw
);
RwLock::new(SCHEMA_DETAIL_FULL.to_string())
}
}
});
#[doc(hidden)]
pub fn parse_audience(s: &str) -> ToolAudience {
match s.to_lowercase().as_str() {
"model" => ToolAudience::Model,
"harness" => ToolAudience::Harness,
"debug" => ToolAudience::Debug,
other => {
eprintln!(
"Warning: Invalid EGGCALC_MCP_AUDIENCE: {:?}. Defaulting to Model. Use Model, Harness, or Debug.",
other
);
ToolAudience::Model
}
}
}
static ACTIVE_AUDIENCE: LazyLock<RwLock<ToolAudience>> = LazyLock::new(|| {
let audience_str =
std::env::var("EGGCALC_MCP_AUDIENCE").unwrap_or_else(|_| "Model".to_string());
RwLock::new(parse_audience(&audience_str))
});
pub fn set_active_profile(name: &str) -> Result<(), String> {
if !registry::PROFILE_NAMES.contains(&name) {
let available: Vec<&str> = registry::PROFILE_NAMES.to_vec();
return Err(format!(
"Unknown profile: {:?}. Available profiles: {}",
name,
available.join(", ")
));
}
let mut profile = ACTIVE_PROFILE.write().map_err(|e| e.to_string())?;
*profile = name.to_string();
Ok(())
}
pub fn get_active_profile() -> String {
let profile = ACTIVE_PROFILE.read().unwrap_or_else(|e| e.into_inner());
profile.clone()
}
pub fn set_schema_detail(level: &str) -> Result<(), String> {
if parse_schema_detail(level).is_none() {
return Err(format!(
"Invalid schema detail: {:?}. Use compact, normal, or full.",
level
));
}
let mut detail = ACTIVE_SCHEMA_DETAIL.write().map_err(|e| e.to_string())?;
*detail = level.to_string();
Ok(())
}
pub fn get_schema_detail() -> String {
let detail = ACTIVE_SCHEMA_DETAIL
.read()
.unwrap_or_else(|e| e.into_inner());
detail.clone()
}
pub fn get_active_audience() -> ToolAudience {
let audience = ACTIVE_AUDIENCE.read().unwrap_or_else(|e| e.into_inner());
*audience
}
pub fn truncate_2000(s: &str) -> String {
s.chars().take(2000).collect()
}
static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);
#[doc(hidden)]
pub struct ActiveRequest {
pub cancel_flag: Arc<AtomicBool>,
#[allow(dead_code)]
pub started_at: Instant,
#[allow(dead_code)]
pub method: String,
pub generation: u64,
}
#[derive(Debug, Clone)]
#[doc(hidden)]
pub struct RequestRegistration {
pub id: Value,
pub generation: u64,
}
#[doc(hidden)]
pub type ActiveRequests = Arc<Mutex<HashMap<Value, ActiveRequest>>>;
#[doc(hidden)]
pub fn new_active_requests() -> ActiveRequests {
Arc::new(Mutex::new(HashMap::new()))
}
pub struct RuntimeMetrics {
pub active_requests: AtomicUsize,
pub active_blocking_handlers: AtomicUsize,
pub timed_out_handlers: AtomicUsize,
pub total_timeouts: AtomicUsize,
pub peak_blocking_concurrency: AtomicUsize,
}
impl RuntimeMetrics {
const fn new() -> Self {
Self {
active_requests: AtomicUsize::new(0),
active_blocking_handlers: AtomicUsize::new(0),
timed_out_handlers: AtomicUsize::new(0),
total_timeouts: AtomicUsize::new(0),
peak_blocking_concurrency: AtomicUsize::new(0),
}
}
#[cfg(test)]
pub fn new_for_test() -> Self {
Self::new()
}
}
#[doc(hidden)]
pub static RUNTIME_METRICS: LazyLock<RuntimeMetrics> = LazyLock::new(RuntimeMetrics::new);
#[doc(hidden)]
pub struct MetricGuard {
counter: &'static AtomicUsize,
}
impl MetricGuard {
pub fn new(counter: &'static AtomicUsize) -> Self {
counter.fetch_add(1, Ordering::Relaxed);
Self { counter }
}
}
impl Drop for MetricGuard {
fn drop(&mut self) {
self.counter.fetch_sub(1, Ordering::Relaxed);
}
}
#[doc(hidden)]
pub struct MetricsSnapshot {
pub active_requests: usize,
pub active_blocking_handlers: usize,
pub timed_out_handlers: usize,
pub total_timeouts: usize,
pub peak_blocking_concurrency: usize,
}
#[doc(hidden)]
pub fn snapshot_metrics() -> MetricsSnapshot {
MetricsSnapshot {
active_requests: RUNTIME_METRICS.active_requests.load(Ordering::Relaxed),
active_blocking_handlers: RUNTIME_METRICS
.active_blocking_handlers
.load(Ordering::Relaxed),
timed_out_handlers: RUNTIME_METRICS.timed_out_handlers.load(Ordering::Relaxed),
total_timeouts: RUNTIME_METRICS.total_timeouts.load(Ordering::Relaxed),
peak_blocking_concurrency: RUNTIME_METRICS
.peak_blocking_concurrency
.load(Ordering::Relaxed),
}
}
#[derive(Debug)]
#[doc(hidden)]
pub enum RegisterRequestError {
DuplicateId,
CapacityExceeded,
}
#[doc(hidden)]
pub async fn register_request(
active: &ActiveRequests,
cancel_flag: &Arc<AtomicBool>,
request_id: Value,
method: String,
) -> Result<(RequestGuard, RequestRegistration), RegisterRequestError> {
let mut map = active.lock().await;
if map.len() >= MAX_IN_FLIGHT_REQUESTS {
return Err(RegisterRequestError::CapacityExceeded);
}
if map.contains_key(&request_id) {
return Err(RegisterRequestError::DuplicateId);
}
let generation = NEXT_GENERATION.fetch_add(1, Ordering::Relaxed);
map.insert(
request_id.clone(),
ActiveRequest {
cancel_flag: cancel_flag.clone(),
started_at: Instant::now(),
method,
generation,
},
);
Ok((
RequestGuard::new(active.clone(), cancel_flag, request_id.clone()),
RequestRegistration {
id: request_id,
generation,
},
))
}
#[doc(hidden)]
pub async fn complete_request(active: &ActiveRequests, registration: &RequestRegistration) -> bool {
let mut map = active.lock().await;
if let Some(entry) = map.get(®istration.id) {
if entry.generation == registration.generation {
map.remove(®istration.id);
return true;
}
}
false
}
#[doc(hidden)]
pub mod test_support {
use super::{ActiveRequest, Instant};
use std::sync::{atomic::AtomicBool, Arc};
pub fn make_active_request(cancel_flag: Arc<AtomicBool>) -> ActiveRequest {
ActiveRequest {
cancel_flag,
started_at: Instant::now(),
method: "test".to_string(),
generation: 0,
}
}
}
#[doc(hidden)]
pub async fn apply_cancellation(active: &ActiveRequests, request_id: &Value) -> bool {
let valid = match request_id {
Value::Bool(_) => return false,
Value::String(s) => s.len() <= MAX_REQUEST_ID_LENGTH,
Value::Number(n) => {
(n.is_i64() || n.is_u64()) && request_id.to_string().len() <= MAX_REQUEST_ID_LENGTH
}
_ => return false,
};
if !valid {
return false;
}
let maybe_flag: Option<Arc<AtomicBool>> = {
let map = active.lock().await;
map.get(request_id).map(|req| req.cancel_flag.clone())
};
if let Some(flag) = maybe_flag {
flag.store(true, Ordering::Release);
true
} else {
false
}
}