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,
generation: u64,
}
impl RequestGuard {
#[doc(hidden)]
pub fn new(
active: ActiveRequests,
_cancel_flag: &Arc<AtomicBool>,
request_id: Value,
generation: u64,
) -> Self {
Self {
active,
request_id,
generation,
}
}
}
impl Drop for RequestGuard {
fn drop(&mut self) {
if let Ok(mut map) = self.active.try_lock() {
if let Some(entry) = map.get(&self.request_id) {
if entry.generation == self.generation {
map.remove(&self.request_id);
}
}
return;
}
let mut map = self.active.blocking_lock();
if let Some(entry) = map.get(&self.request_id) {
if entry.generation == self.generation {
map.remove(&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 MODERN_PROTOCOL_VERSION: &str = "2026-07-28";
pub const LEGACY_SUPPORTED_VERSIONS: &[&str] = &["2025-11-25", "2024-11-05"];
pub const LEGACY_PREFERRED_VERSION: &str = LEGACY_SUPPORTED_VERSIONS[0];
pub const SUPPORTED_PROTOCOL_VERSIONS: &[&str] = &["2026-07-28", "2025-11-25", "2024-11-05"];
pub const PREFERRED_PROTOCOL_VERSION: &str = SUPPORTED_PROTOCOL_VERSIONS[0];
pub const MCP_PROTOCOL_VERSION: &str = LEGACY_PREFERRED_VERSION;
pub const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
pub const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";
pub const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
pub const META_SERVER_INFO: &str = "io.modelcontextprotocol/serverInfo";
pub const EGGSACT_META_NAMESPACE: &str = "io.github.eggstack/eggsact";
pub const MODERN_CACHE_TTL_MS: u64 = 3_600_000;
pub const MODERN_CACHE_SCOPE: &str = "public";
pub const SERVER_INSTRUCTIONS: &str = "eggsact is a local deterministic utility server. Preflight and inspection tools analyze inputs and report findings, verdicts, and machine codes; they do not execute changes. Tool results carry structuredContent conforming to outputSchema plus a text JSON fallback.";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProtocolEra {
Legacy,
Modern20260728,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConnectionEra {
Undecided,
Legacy,
Modern20260728,
}
impl ConnectionEra {
pub fn is_decided(self) -> bool {
!matches!(self, ConnectionEra::Undecided)
}
pub fn as_str(self) -> &'static str {
match self {
ConnectionEra::Undecided => "undecided",
ConnectionEra::Legacy => "legacy",
ConnectionEra::Modern20260728 => "modern",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EraPinOutcome {
PinnedNow,
AlreadyPinned,
Mismatch,
}
pub fn try_pin_era(state: &mut ConnectionEra, target: ConnectionEra) -> EraPinOutcome {
match (*state, target) {
(ConnectionEra::Undecided, ConnectionEra::Undecided) => EraPinOutcome::AlreadyPinned,
(ConnectionEra::Undecided, decided) => {
*state = decided;
EraPinOutcome::PinnedNow
}
(current, target) if current == target => EraPinOutcome::AlreadyPinned,
_ => EraPinOutcome::Mismatch,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InboundEraClassification {
Legacy,
Modern20260728,
InvalidModernEnvelope,
Unsupported { requested: String },
}
pub fn classify_inbound_era(method: &str, params: Option<&Value>) -> InboundEraClassification {
let params_obj = params.and_then(Value::as_object);
let meta_value = params_obj.and_then(|obj| obj.get("_meta"));
if method == "initialize" {
let modern_claim = meta_value
.and_then(Value::as_object)
.and_then(|meta| meta.get(META_PROTOCOL_VERSION))
.and_then(Value::as_str)
.is_some_and(is_modern_supported_version);
return if modern_claim {
InboundEraClassification::Modern20260728
} else {
InboundEraClassification::Legacy
};
}
let Some(meta_value) = meta_value else {
return InboundEraClassification::Legacy;
};
let Some(meta) = meta_value.as_object() else {
return InboundEraClassification::InvalidModernEnvelope;
};
let Some(version_value) = meta.get(META_PROTOCOL_VERSION) else {
return InboundEraClassification::InvalidModernEnvelope;
};
let Some(version) = version_value.as_str() else {
return InboundEraClassification::InvalidModernEnvelope;
};
if is_modern_supported_version(version) {
InboundEraClassification::Modern20260728
} else {
InboundEraClassification::Unsupported {
requested: version.to_string(),
}
}
}
pub async fn pin_connection_era(
era: &Arc<Mutex<ConnectionEra>>,
target: ConnectionEra,
) -> EraPinOutcome {
let mut guard = era.lock().await;
try_pin_era(&mut guard, target)
}
pub async fn current_connection_era(era: &Arc<Mutex<ConnectionEra>>) -> ConnectionEra {
*era.lock().await
}
#[derive(Debug, Clone)]
pub struct ModernRequestContext {
pub protocol_version: String,
pub client_name: Option<String>,
pub client_version: Option<String>,
pub client_capabilities: Value,
}
impl ModernRequestContext {
pub fn era(&self) -> ProtocolEra {
ProtocolEra::Modern20260728
}
}
pub fn is_supported_protocol_version(version: &str) -> bool {
SUPPORTED_PROTOCOL_VERSIONS.contains(&version)
}
pub fn is_legacy_supported_version(version: &str) -> bool {
LEGACY_SUPPORTED_VERSIONS.contains(&version)
}
pub fn is_modern_supported_version(version: &str) -> bool {
version == MODERN_PROTOCOL_VERSION
}
pub fn negotiate_legacy_version(requested: &str) -> String {
if is_legacy_supported_version(requested) {
requested.to_string()
} else {
LEGACY_PREFERRED_VERSION.to_string()
}
}
pub fn negotiate_protocol_version(requested: &str) -> String {
negotiate_legacy_version(requested)
}
pub fn parse_modern_request_meta(
params: Option<&Value>,
) -> Option<Result<ModernRequestContext, Value>> {
let params_obj = params?.as_object()?;
let meta = params_obj.get("_meta")?;
let meta_obj = match meta.as_object() {
Some(o) => o,
None => {
return Some(Err(crate::mcp::protocol::invalid_params(
"Invalid params: '_meta' must be an object",
None,
)));
}
};
let version_value = match meta_obj.get(META_PROTOCOL_VERSION) {
Some(v) => v,
None => {
return Some(Err(crate::mcp::protocol::invalid_params(
"Invalid params: '_meta.io.modelcontextprotocol/protocolVersion' is required for modern requests",
None,
)));
}
};
let version_str = match version_value.as_str() {
Some(s) => s,
None => {
return Some(Err(crate::mcp::protocol::invalid_params(
"Invalid params: '_meta.io.modelcontextprotocol/protocolVersion' must be a string",
None,
)));
}
};
if !is_modern_supported_version(version_str) {
return Some(Err(crate::mcp::protocol::unsupported_protocol_version(
version_str,
None,
)));
}
let caps = match meta_obj.get(META_CLIENT_CAPABILITIES) {
Some(v) => v,
None => {
return Some(Err(crate::mcp::protocol::invalid_params(
"Invalid params: '_meta.io.modelcontextprotocol/clientCapabilities' is required for modern requests",
None,
)));
}
};
if !caps.is_object() {
return Some(Err(crate::mcp::protocol::invalid_params(
"Invalid params: '_meta.io.modelcontextprotocol/clientCapabilities' must be an object",
None,
)));
}
let (client_name, client_version) = match meta_obj.get(META_CLIENT_INFO) {
None => (None, None),
Some(v) => {
let obj = match v.as_object() {
Some(o) => o,
None => {
return Some(Err(crate::mcp::protocol::invalid_params(
"Invalid params: '_meta.io.modelcontextprotocol/clientInfo' must be an object",
None,
)));
}
};
let name = match obj.get("name").and_then(|n| n.as_str()) {
Some(n) if !n.is_empty() => n.to_string(),
_ => {
return Some(Err(crate::mcp::protocol::invalid_params(
"Invalid params: '_meta.io.modelcontextprotocol/clientInfo.name' must be a non-empty string",
None,
)));
}
};
let version = obj
.get("version")
.and_then(|n| n.as_str())
.map(|s| s.to_string());
(Some(name), version)
}
};
Some(Ok(ModernRequestContext {
protocol_version: version_str.to_string(),
client_name,
client_version,
client_capabilities: caps.clone(),
}))
}
#[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")
);
}
}
#[cfg(test)]
mod connection_era_tests {
use super::*;
#[test]
fn undecided_pins_once_and_rejects_cross_era() {
let mut era = ConnectionEra::Undecided;
assert!(!era.is_decided());
assert_eq!(
try_pin_era(&mut era, ConnectionEra::Legacy),
EraPinOutcome::PinnedNow
);
assert!(era.is_decided());
assert_eq!(era, ConnectionEra::Legacy);
assert_eq!(
try_pin_era(&mut era, ConnectionEra::Legacy),
EraPinOutcome::AlreadyPinned
);
assert_eq!(
try_pin_era(&mut era, ConnectionEra::Modern20260728),
EraPinOutcome::Mismatch
);
assert_eq!(era, ConnectionEra::Legacy);
}
#[test]
fn modern_pins_once_and_rejects_legacy() {
let mut era = ConnectionEra::Undecided;
assert_eq!(
try_pin_era(&mut era, ConnectionEra::Modern20260728),
EraPinOutcome::PinnedNow
);
assert_eq!(era, ConnectionEra::Modern20260728);
assert_eq!(
try_pin_era(&mut era, ConnectionEra::Legacy),
EraPinOutcome::Mismatch
);
assert_eq!(era, ConnectionEra::Modern20260728);
}
#[test]
fn invalid_opening_leaves_undecided() {
let era = ConnectionEra::Undecided;
assert_eq!(era.as_str(), "undecided");
assert_eq!(ConnectionEra::Legacy.as_str(), "legacy");
assert_eq!(ConnectionEra::Modern20260728.as_str(), "modern");
}
#[test]
fn edge_classifier_distinguishes_claimless_valid_invalid_and_unsupported() {
assert_eq!(
classify_inbound_era("ping", None),
InboundEraClassification::Legacy
);
assert_eq!(
classify_inbound_era("server/discover", None),
InboundEraClassification::Legacy
);
assert_eq!(
classify_inbound_era(
"tools/list",
Some(&serde_json::json!({"_meta": {
"io.modelcontextprotocol/protocolVersion": MODERN_PROTOCOL_VERSION,
"io.modelcontextprotocol/clientCapabilities": {},
}}))
),
InboundEraClassification::Modern20260728
);
assert_eq!(
classify_inbound_era(
"tools/list",
Some(&serde_json::json!({"_meta": {
"io.modelcontextprotocol/protocolVersion": "1900-01-01",
}}))
),
InboundEraClassification::Unsupported {
requested: "1900-01-01".to_string()
}
);
assert_eq!(
classify_inbound_era(
"tools/list",
Some(&serde_json::json!({"_meta": {
"io.modelcontextprotocol/protocolVersion": MODERN_PROTOCOL_VERSION,
}}))
),
InboundEraClassification::Modern20260728
);
assert_eq!(
classify_inbound_era(
"tools/list",
Some(&serde_json::json!({"_meta": {
"io.modelcontextprotocol/protocolVersion": 20260728,
}}))
),
InboundEraClassification::InvalidModernEnvelope
);
}
#[tokio::test]
async fn concurrent_opening_attempts_have_single_winner() {
let era = Arc::new(Mutex::new(ConnectionEra::Undecided));
let a = era.clone();
let b = era.clone();
let (ra, rb) = tokio::join!(
pin_connection_era(&a, ConnectionEra::Legacy),
pin_connection_era(&b, ConnectionEra::Modern20260728),
);
let pinned_count = [ra, rb]
.iter()
.filter(|o| **o == EraPinOutcome::PinnedNow)
.count();
assert_eq!(
pinned_count, 1,
"exactly one opening era must win, got {:?} and {:?}",
ra, rb
);
assert!(
[ra, rb].contains(&EraPinOutcome::Mismatch),
"loser must observe mismatch, got {:?} and {:?}",
ra,
rb
);
let final_era = current_connection_era(&era).await;
assert!(
matches!(
final_era,
ConnectionEra::Legacy | ConnectionEra::Modern20260728
),
"final era must be decided, got {:?}",
final_era
);
match ra {
EraPinOutcome::PinnedNow => assert_eq!(final_era, ConnectionEra::Legacy),
EraPinOutcome::Mismatch => assert_eq!(final_era, ConnectionEra::Modern20260728),
EraPinOutcome::AlreadyPinned => panic!("unexpected AlreadyPinned for ra"),
}
}
}
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 {
eprintln!(
"Warning: Invalid EGGCALC_MCP_PROFILE: {:?}. Available profiles: {}. Defaulting to full.",
profile,
registry::PROFILE_NAMES.join(", ")
);
"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
}
#[doc(hidden)]
pub fn parse_surface(s: &str) -> Option<crate::mcp::discovery::McpSurface> {
crate::mcp::discovery::McpSurface::parse(s)
}
static ACTIVE_SURFACE: LazyLock<RwLock<crate::mcp::discovery::McpSurface>> = LazyLock::new(|| {
let raw = std::env::var("EGGSACT_MCP_SURFACE").unwrap_or_else(|_| "direct".to_string());
match crate::mcp::discovery::McpSurface::parse(&raw) {
Some(surface) => RwLock::new(surface),
None => {
eprintln!(
"Warning: Invalid EGGSACT_MCP_SURFACE: {:?}. Accepted values: direct, discovery. Defaulting to direct.",
raw
);
RwLock::new(crate::mcp::discovery::McpSurface::Direct)
}
}
});
pub fn init_active_surface() -> Result<(), String> {
let raw = std::env::var("EGGSACT_MCP_SURFACE").unwrap_or_else(|_| "direct".to_string());
match crate::mcp::discovery::McpSurface::parse(&raw) {
Some(surface) => set_active_surface(surface),
None => Err(format!(
"Invalid EGGSACT_MCP_SURFACE: {:?}. Accepted values: direct, discovery.",
raw
)),
}
}
pub fn set_active_surface(surface: crate::mcp::discovery::McpSurface) -> Result<(), String> {
let mut active = ACTIVE_SURFACE.write().map_err(|e| e.to_string())?;
*active = surface;
Ok(())
}
pub fn get_active_surface() -> crate::mcp::discovery::McpSurface {
let surface = ACTIVE_SURFACE.read().unwrap_or_else(|e| e.into_inner());
*surface
}
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(), generation),
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
}
}