use crate::agent::{Profile, ToolAudience, ToolCallError, ToolRegistry};
use crate::mcp::budget::budget_for_tool;
use crate::mcp::compat::CompatibilityMode;
use crate::mcp::execution;
use crate::mcp::machine_codes;
use crate::mcp::protocol::{
already_initialized, invalid_params, invalid_request, json_rpc_error, json_rpc_error_with_data,
method_not_found, not_initialized, server_info_meta, unsupported_protocol_version,
unsupported_protocol_version_without_requested, with_request_id, DiscoverResult,
EggsactExtensions, ExperimentalCapabilities, InitializeParams, InitializeResult,
JsonRpcRequest, JsonRpcResponse, ServerCapabilities, ServerInfo, ToolsCapability,
};
use crate::mcp::registry;
use crate::mcp::response::{wrap_tool_response, wrap_tool_response_modern, ToolResponse};
use crate::mcp::runtime::{
apply_cancellation, classify_inbound_era, complete_request, current_connection_era,
get_active_audience, get_active_profile, get_active_surface, get_schema_detail,
negotiate_legacy_version, new_active_requests, parse_modern_request_meta, pin_connection_era,
register_request, ConnectionEra, EraPinOutcome, InboundEraClassification, MetricGuard,
ModernRequestContext, NegotiatedProtocol, RegisterRequestError, SessionState,
MAX_REQUEST_BYTES, MAX_REQUEST_ID_LENGTH, MAX_TOOL_WORKERS, MCP_SERVER_NAME,
MODERN_CACHE_SCOPE, MODERN_CACHE_TTL_MS, MODERN_PROTOCOL_VERSION, RUNTIME_METRICS,
SERVER_INSTRUCTIONS,
};
use serde_json::Value;
use std::io::Write;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::sync::Mutex;
pub fn mcp_tool_count() -> usize {
registry::tool_count()
}
fn truncate_utf8_bytes(input: &str, max_bytes: usize, suffix: &str) -> String {
if input.len() <= max_bytes {
return input.to_string();
}
let suffix_bytes = suffix.len();
if suffix_bytes >= max_bytes {
return suffix.to_string();
}
let mut end = max_bytes - suffix_bytes;
while end > 0 && !input.is_char_boundary(end) {
end -= 1;
}
let mut result = String::with_capacity(max_bytes);
result.push_str(&input[..end]);
result.push_str(suffix);
result
}
fn truncate_id_display(id: &Value) -> String {
let s = id.to_string();
truncate_utf8_bytes(&s, 128, "...")
}
#[derive(Debug)]
enum LimitedLine {
Line(String),
TooLarge { observed_at_least: usize },
Eof,
}
async fn read_bounded_line<R: tokio::io::AsyncBufRead + Unpin>(
reader: &mut R,
max_bytes: usize,
) -> LimitedLine {
let mut buf: Vec<u8> = Vec::with_capacity(max_bytes);
let mut bytes_before_lf: usize = 0;
let mut last_byte: Option<u8> = None;
let mut io_errored = false;
loop {
let chunk = match reader.fill_buf().await {
Ok(c) => c,
Err(e) => {
eprintln!(
"warning: read_bounded_line I/O error after {bytes_before_lf} bytes: {e}"
);
io_errored = true;
break;
}
};
if chunk.is_empty() {
break;
}
let chunk_len = chunk.len();
let last_chunk_byte = *chunk.last().expect("non-empty chunk has a last byte");
let newline_pos = chunk.iter().position(|&b| b == b'\n');
let byte_before_lf = newline_pos.and_then(|pos| {
if pos == 0 {
last_byte
} else {
Some(chunk[pos - 1])
}
});
if let Some(pos) = newline_pos {
let crlf = byte_before_lf == Some(b'\r');
let line_bytes = bytes_before_lf
.saturating_add(pos)
.saturating_sub(usize::from(crlf));
if line_bytes > max_bytes {
reader.consume(pos + 1);
return LimitedLine::TooLarge {
observed_at_least: line_bytes,
};
}
if crlf && pos == 0 && buf.last() == Some(&b'\r') {
buf.pop();
}
let payload_in_chunk = if pos > 0 && crlf { pos - 1 } else { pos };
let can_take = max_bytes.saturating_sub(buf.len()).min(payload_in_chunk);
if can_take > 0 {
buf.extend_from_slice(&chunk[..can_take]);
}
reader.consume(pos + 1);
return LimitedLine::Line(string_from_utf8_lossy(&buf));
}
let can_take = max_bytes.saturating_sub(buf.len()).min(chunk_len);
if can_take > 0 {
buf.extend_from_slice(&chunk[..can_take]);
}
bytes_before_lf = bytes_before_lf.saturating_add(chunk_len);
last_byte = Some(last_chunk_byte);
reader.consume(chunk_len);
}
if io_errored {
LimitedLine::Eof
} else if bytes_before_lf > max_bytes {
LimitedLine::TooLarge {
observed_at_least: bytes_before_lf,
}
} else if buf.is_empty() {
LimitedLine::Eof
} else {
LimitedLine::Line(string_from_utf8_lossy(&buf))
}
}
fn string_from_utf8_lossy(bytes: &[u8]) -> String {
String::from_utf8(bytes.to_vec())
.unwrap_or_else(|e| String::from_utf8_lossy(&e.into_bytes()).into_owned())
}
fn write_json_line(value: &Value, scratch: &mut Vec<u8>) -> std::io::Result<()> {
scratch.clear();
serde_json::to_writer(&mut *scratch, value).map_err(std::io::Error::other)?;
scratch.push(b'\n');
let mut stdout = std::io::stdout().lock();
stdout.write_all(scratch)?;
stdout.flush()
}
fn build_server_capabilities() -> ServerCapabilities {
ServerCapabilities {
tools: ToolsCapability {
list_changed: false,
},
experimental: Some(ExperimentalCapabilities {
eggsact: EggsactExtensions {
profiles: true,
schema_detail: true,
audience_filtering: true,
},
}),
}
}
fn build_discover_value() -> Value {
serde_json::to_value(DiscoverResult::current(build_server_capabilities())).unwrap_or_else(
|_| {
serde_json::json!({
"resultType": "complete",
"supportedVersions": crate::mcp::runtime::SUPPORTED_PROTOCOL_VERSIONS,
"capabilities": {"tools": {"listChanged": false}},
"instructions": SERVER_INSTRUCTIONS,
"ttlMs": MODERN_CACHE_TTL_MS,
"cacheScope": MODERN_CACHE_SCOPE,
"_meta": server_info_meta(),
})
},
)
}
struct ToolsListFilters {
schema_detail: Option<String>,
names: Option<Vec<String>>,
profile: Option<String>,
audience: Option<String>,
tier: Option<u8>,
tags: Option<Vec<String>>,
}
fn parse_tools_list_params(
params: Option<&Value>,
id: &Option<Value>,
) -> Result<ToolsListFilters, Value> {
if let Some(p) = params {
if !p.is_object() {
return Err(invalid_request(
"Invalid params: expected object",
id.clone(),
));
}
}
if let Some(p) = params {
if let Some(d) = p.get("schema_detail") {
if !d.is_string() || !matches!(d.as_str(), Some("compact" | "normal" | "full")) {
return Err(invalid_request(
"Invalid 'schema_detail' parameter: expected compact, normal, or full",
id.clone(),
));
}
}
if let Some(t) = p.get("tier") {
if !t.is_i64() && !t.is_u64() && !t.is_boolean() {
return Err(invalid_request(
"Invalid 'tier' parameter: expected integer",
id.clone(),
));
}
}
if let Some(t) = p.get("tags") {
match t.as_array() {
Some(tags) if tags.iter().all(|v| v.is_string()) => {}
Some(_) => {
return Err(invalid_request(
"Invalid 'tags' parameter: all items must be strings",
id.clone(),
));
}
None => {
return Err(invalid_request(
"Invalid 'tags' parameter: expected array",
id.clone(),
));
}
}
}
if let Some(n) = p.get("names") {
match n.as_array() {
Some(names) if names.iter().all(|v| v.is_string()) => {}
Some(_) => {
return Err(invalid_request(
"Invalid 'names' parameter: all items must be strings",
id.clone(),
));
}
None => {
return Err(invalid_request(
"Invalid 'names' parameter: expected array",
id.clone(),
));
}
}
}
if let Some(pr) = p.get("profile") {
if !pr.is_string() {
return Err(invalid_request(
"Invalid 'profile' parameter: expected string",
id.clone(),
));
}
}
if let Some(a) = p.get("audience") {
if !a.is_string() || !matches!(a.as_str(), Some("model" | "harness" | "debug")) {
return Err(invalid_request(
"Invalid 'audience' parameter: expected model, harness, or debug",
id.clone(),
));
}
}
}
let schema_detail = params
.and_then(|p| p.get("schema_detail"))
.and_then(|d| d.as_str())
.map(String::from);
let names = params
.and_then(|p| p.get("names"))
.and_then(|n| n.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect::<Vec<String>>()
});
let profile = params
.and_then(|p| p.get("profile"))
.and_then(|p| p.as_str())
.map(String::from);
let audience = params
.and_then(|p| p.get("audience"))
.and_then(|a| a.as_str())
.map(String::from);
let tier = params.and_then(|p| p.get("tier")).and_then(|t| match t {
Value::Number(n) => n.as_u64().map(|v| v as u8),
Value::Bool(b) => Some(if *b { 1 } else { 0 }),
_ => None,
});
let tags = params
.and_then(|p| p.get("tags"))
.and_then(|t| t.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect::<Vec<String>>()
});
Ok(ToolsListFilters {
schema_detail,
names,
profile,
audience,
tier,
tags,
})
}
fn handle_tools_list_shared(
params: Option<&Value>,
id: Option<Value>,
modern: bool,
) -> Option<Value> {
let filters = match parse_tools_list_params(params, &id) {
Ok(f) => f,
Err(e) => return Some(e),
};
let default_detail = get_schema_detail();
let detail = filters.schema_detail.as_deref().unwrap_or(&default_detail);
let active_profile = get_active_profile();
let effective_profile = filters.profile.as_deref().unwrap_or(&active_profile);
let effective_audience_str =
filters
.audience
.as_deref()
.unwrap_or_else(|| match get_active_audience() {
ToolAudience::Model => "model",
ToolAudience::Harness => "harness",
ToolAudience::Debug => "debug",
});
if effective_profile != "full" && !registry::PROFILE_NAMES.contains(&effective_profile) {
let available = registry::PROFILE_NAMES.join(", ");
return Some(serde_json::json!({
"jsonrpc": "2.0",
"error": {
"code": -32602,
"message": format!("Unknown MCP profile: '{}'. Available profiles: {}", effective_profile, available)
},
"id": id
}));
}
let audience_enum = match effective_audience_str {
"harness" => registry::ToolListAudience::Harness,
"debug" => registry::ToolListAudience::Debug,
_ => registry::ToolListAudience::Model,
};
let audience = Some(audience_enum);
if get_active_surface() == crate::mcp::discovery::McpSurface::Discovery {
if modern {
let tools = crate::mcp::discovery::discovery_modern_values(
effective_profile,
audience_enum,
filters.names.as_deref(),
);
return Some(serde_json::json!({
"resultType": "complete",
"tools": tools,
"ttlMs": MODERN_CACHE_TTL_MS,
"cacheScope": MODERN_CACHE_SCOPE,
"_meta": server_info_meta(),
}));
} else {
let tools = crate::mcp::discovery::discovery_legacy_definitions(
effective_profile,
audience_enum,
filters.names.as_deref(),
);
return Some(serde_json::json!({"tools": tools}));
}
}
let effective_profile_owned: String = effective_profile.to_string();
let detail_owned: String = detail.to_string();
let options = registry::ToolListOptions {
profile: &effective_profile_owned,
names: filters.names.as_deref(),
tier: filters.tier,
tags: filters.tags.as_deref(),
schema_detail: &detail_owned,
audience,
};
if modern {
let tools = registry::list_modern_tool_values(options);
Some(serde_json::json!({
"resultType": "complete",
"tools": tools,
"ttlMs": MODERN_CACHE_TTL_MS,
"cacheScope": MODERN_CACHE_SCOPE,
"_meta": server_info_meta(),
}))
} else {
let tools = registry::list_tool_definitions(options);
Some(serde_json::json!({"tools": tools}))
}
}
fn handle_profiles_list_shared(
params: Option<&Value>,
id: Option<Value>,
modern: bool,
) -> Option<Value> {
if let Some(p) = params {
if !p.is_object() {
return Some(invalid_request(
"Invalid params: expected object",
id.clone(),
));
}
}
let active = get_active_profile();
let mut profiles_info = serde_json::Map::new();
for &name in registry::PROFILE_NAMES {
let tool_specs = registry::tools_for_profile(name);
let mut tool_names: Vec<Value> = tool_specs
.into_iter()
.map(|spec| Value::String(spec.name.to_string()))
.collect();
tool_names.sort_by(|a, b| a.as_str().unwrap_or("").cmp(b.as_str().unwrap_or("")));
profiles_info.insert(
name.to_string(),
serde_json::json!({
"tools": tool_names,
"tool_count": tool_names.len(),
}),
);
}
if modern {
Some(serde_json::json!({
"resultType": "complete",
"active_profile": active,
"profiles": Value::Object(profiles_info),
"available_profiles": registry::PROFILE_NAMES,
"_meta": server_info_meta(),
}))
} else {
Some(serde_json::json!({
"active_profile": active,
"profiles": Value::Object(profiles_info),
"available_profiles": registry::PROFILE_NAMES,
}))
}
}
async fn handle_tool_search_facade(
arguments_val: &Value,
active_profile: &str,
active_audience: ToolAudience,
id: Option<Value>,
modern: bool,
) -> Option<Value> {
let params = match crate::mcp::discovery::parse_search_params(arguments_val) {
Ok(p) => p,
Err(msg) => {
return Some(json_rpc_error(
-32602,
format!("Invalid arguments for tool 'tool_search': {}", msg),
id.clone(),
));
}
};
let registry_audience = active_audience.as_registry_audience();
let specs = registry::tools_for_profile_audience(active_profile, registry_audience);
let hits = crate::mcp::discovery::search_filtered(&specs, ¶ms);
let matches = crate::mcp::discovery::matches_value(&hits, params.detail_schema);
let result = serde_json::json!({
"matches": matches,
"query": params.query,
});
let mut response = ToolResponse::success(result, Some(crate::mcp::discovery::TOOL_SEARCH));
let budget = crate::mcp::budget::ToolBudget::CHEAP;
crate::mcp::response::truncate_response(&mut response, &budget);
if modern {
Some(wrap_tool_response_modern(&response))
} else {
Some(wrap_tool_response(&response))
}
}
#[allow(clippy::too_many_arguments)]
async fn handle_tool_invoke_facade(
arguments_val: &Value,
active_profile: &str,
active_audience: ToolAudience,
cancel_flag: &Arc<std::sync::atomic::AtomicBool>,
tool_semaphore: &Arc<tokio::sync::Semaphore>,
id: Option<Value>,
modern: bool,
) -> Option<Value> {
let invoke = match crate::mcp::discovery::parse_invoke_params(arguments_val) {
Ok(p) => p,
Err(msg) => {
return Some(json_rpc_error(
-32602,
format!("Invalid arguments for tool 'tool_invoke': {}", msg),
id.clone(),
));
}
};
let target = invoke.target;
let target_args = invoke.arguments;
let profile =
Profile::from_str_opt(active_profile).unwrap_or_else(|| Profile::custom(active_profile));
let tool_registry = ToolRegistry::with_profile_and_audience(profile.clone(), active_audience)
.with_compat_mode(CompatibilityMode::EggcalcPython);
let prepared = match tool_registry.prepare_tool_call_internal(
&target,
&target_args,
&profile,
active_audience,
CompatibilityMode::EggcalcPython,
) {
Ok(prepared) => prepared,
Err(e) => {
return match e {
ToolCallError::UnknownTool(tool_name) => {
let tool_names = registry::tool_names();
let msg = match registry::find_close_match(&tool_name, &tool_names) {
Some(m) => format!("Unknown tool: {}. Did you mean: {}?", tool_name, m),
None => format!("Unknown tool: {}", tool_name),
};
Some(method_not_found(msg, id.clone()))
}
ToolCallError::ToolUnavailable { tool, profile } => Some(json_rpc_error(
-32602,
format!(
"Tool '{}' is not available in profile '{}'. Check the tool's declared profiles, or switch to a profile that includes it.",
tool, profile
),
id.clone(),
)),
ToolCallError::ToolNotAllowedForAudience {
tool,
profile,
audience,
exposure,
} => Some(json_rpc_error(
-32602,
format!(
"Tool '{}' (exposure: {}) cannot be executed by {} audience in profile '{}'. Use tools/list with appropriate audience, or use the in-process API with a different audience.",
tool, exposure, audience, profile
),
id.clone(),
)),
ToolCallError::InvalidArguments(msg) => Some(json_rpc_error(
-32602,
format!("Invalid arguments for tool '{}': {}", target, msg),
id.clone(),
)),
ToolCallError::Internal(msg) => Some(json_rpc_error(-32603, msg, id.clone())),
};
}
};
let sem = tool_semaphore.clone();
let handler = prepared.handler;
let tool_budget = budget_for_tool(&target, prepared.cost);
let outcome = execution::execute_tool_bounded(
handler,
target_args,
target.clone(),
tool_budget,
cancel_flag.clone(),
sem,
)
.await;
if modern {
Some(execution::build_tool_response_modern(
outcome,
&target,
&tool_budget,
id.clone(),
))
} else {
Some(execution::build_tool_response(
outcome,
&target,
&tool_budget,
id.clone(),
))
}
}
async fn handle_tools_call_shared(
params: Option<&Value>,
cancel_flag: &Arc<std::sync::atomic::AtomicBool>,
tool_semaphore: &Arc<tokio::sync::Semaphore>,
id: Option<Value>,
modern: bool,
) -> Option<Value> {
let params_obj = match params {
Some(p) => {
if !p.is_object() {
return Some(invalid_request(
"Invalid params: expected object",
id.clone(),
));
}
p
}
None => {
return Some(invalid_request(
"Invalid params: expected object",
id.clone(),
));
}
};
let name = match params_obj.get("name").and_then(|v| v.as_str()) {
Some(n) => n,
None => {
return Some(invalid_request(
"Invalid params: missing tool name",
id.clone(),
));
}
};
let arguments_val = match params_obj.get("arguments") {
Some(v) if v.is_object() => v.clone(),
Some(_) => {
return Some(invalid_request(
"Invalid arguments: expected object",
id.clone(),
));
}
None => Value::Object(serde_json::Map::new()),
};
if cancel_flag.load(Ordering::Acquire) {
let cancelled = ToolResponse::error_with_code(
"cancelled",
machine_codes::CANCELLED,
&format!("Tool '{}' request was cancelled by the client", name),
Some(vec![
"The request was cancelled before execution started".to_string()
]),
Some(name),
);
if modern {
return Some(wrap_tool_response_modern(&cancelled));
} else {
return Some(wrap_tool_response(&cancelled));
}
}
let active_profile = get_active_profile();
let profile =
Profile::from_str_opt(&active_profile).unwrap_or_else(|| Profile::custom(&active_profile));
let active_audience = get_active_audience();
let surface = get_active_surface();
if crate::mcp::discovery::is_discovery_facade(name) {
if surface != crate::mcp::discovery::McpSurface::Discovery {
let tool_names = registry::tool_names();
let msg = match registry::find_close_match(name, &tool_names) {
Some(m) => format!(
"Unknown tool: {}. Did you mean: {}? (discovery facades require EGGSACT_MCP_SURFACE=discovery or --mcp-surface discovery)",
name, m
),
None => format!(
"Unknown tool: {} (discovery facades require EGGSACT_MCP_SURFACE=discovery or --mcp-surface discovery)",
name
),
};
return Some(method_not_found(msg, id.clone()));
}
if name == crate::mcp::discovery::TOOL_SEARCH {
return handle_tool_search_facade(
&arguments_val,
&active_profile,
active_audience,
id,
modern,
)
.await;
}
if name == crate::mcp::discovery::TOOL_INVOKE {
return handle_tool_invoke_facade(
&arguments_val,
&active_profile,
active_audience,
cancel_flag,
tool_semaphore,
id,
modern,
)
.await;
}
}
let tool_registry = ToolRegistry::with_profile_and_audience(profile.clone(), active_audience)
.with_compat_mode(CompatibilityMode::EggcalcPython);
let prepared = match tool_registry.prepare_tool_call_internal(
name,
&arguments_val,
&profile,
active_audience,
CompatibilityMode::EggcalcPython,
) {
Ok(prepared) => prepared,
Err(e) => {
return match e {
ToolCallError::UnknownTool(tool_name) => {
let tool_names = registry::tool_names();
let msg = match registry::find_close_match(&tool_name, &tool_names) {
Some(m) => format!("Unknown tool: {}. Did you mean: {}?", tool_name, m),
None => format!("Unknown tool: {}", tool_name),
};
Some(method_not_found(msg, id.clone()))
}
ToolCallError::ToolUnavailable { tool, profile } => Some(json_rpc_error(
-32602,
format!(
"Tool '{}' is not available in profile '{}'. Check the tool's declared profiles, or switch to a profile that includes it.",
tool, profile
),
id.clone(),
)),
ToolCallError::ToolNotAllowedForAudience {
tool,
profile,
audience,
exposure,
} => Some(json_rpc_error(
-32602,
format!(
"Tool '{}' (exposure: {}) cannot be executed by {} audience in profile '{}'. Use tools/list with appropriate audience, or use the in-process API with a different audience.",
tool, exposure, audience, profile
),
id.clone(),
)),
ToolCallError::InvalidArguments(msg) => Some(json_rpc_error(
-32602,
format!("Invalid arguments for tool '{}': {}", name, msg),
id.clone(),
)),
ToolCallError::Internal(msg) => Some(json_rpc_error(-32603, msg, id.clone())),
};
}
};
let name_owned = name.to_string();
let sem = tool_semaphore.clone();
let handler = prepared.handler;
let tool_budget = budget_for_tool(name, prepared.cost);
let outcome = execution::execute_tool_bounded(
handler,
arguments_val,
name_owned.clone(),
tool_budget,
cancel_flag.clone(),
sem,
)
.await;
if modern {
Some(execution::build_tool_response_modern(
outcome,
&name_owned,
&tool_budget,
id.clone(),
))
} else {
Some(execution::build_tool_response(
outcome,
&name_owned,
&tool_budget,
id.clone(),
))
}
}
async fn handle_request_async(
request: &JsonRpcRequest,
cancel_flag: &Arc<std::sync::atomic::AtomicBool>,
tool_semaphore: &Arc<tokio::sync::Semaphore>,
session_state: &Arc<Mutex<SessionState>>,
connection_era: &Arc<Mutex<ConnectionEra>>,
) -> Option<serde_json::Value> {
let method = request.method.as_str();
let classification = classify_inbound_era(method, request.params.as_ref());
let modern_ctx: Option<ModernRequestContext> = match &classification {
InboundEraClassification::Modern20260728 => {
match parse_modern_request_meta(request.params.as_ref()) {
Some(Ok(ctx)) => Some(ctx),
Some(Err(e)) => return Some(with_request_id(e, request.id.clone())),
None => {
return Some(invalid_params(
"Invalid params: modern request envelope is required",
request.id.clone(),
))
}
}
}
InboundEraClassification::InvalidModernEnvelope => {
return Some(match parse_modern_request_meta(request.params.as_ref()) {
Some(Err(e)) => with_request_id(e, request.id.clone()),
_ => invalid_params(
"Invalid params: malformed modern request envelope",
request.id.clone(),
),
});
}
InboundEraClassification::Unsupported { requested } => {
return Some(unsupported_protocol_version(requested, request.id.clone()));
}
InboundEraClassification::Legacy => None,
};
let target_era = if modern_ctx.is_some() {
ConnectionEra::Modern20260728
} else {
ConnectionEra::Legacy
};
match pin_connection_era(connection_era, target_era).await {
EraPinOutcome::PinnedNow | EraPinOutcome::AlreadyPinned => {}
EraPinOutcome::Mismatch => {
return Some(match target_era {
ConnectionEra::Modern20260728 => {
unsupported_protocol_version(MODERN_PROTOCOL_VERSION, request.id.clone())
}
ConnectionEra::Legacy => {
unsupported_protocol_version_without_requested(request.id.clone())
}
ConnectionEra::Undecided => unreachable!("request target is always decided"),
});
}
}
if modern_ctx.is_some() {
match method {
"server/discover" => {
return Some(build_discover_value());
}
"initialize" => {
return Some(method_not_found(
"Method not found: initialize (legacy handshake is not part of the 2026-07-28 era; use server/discover)",
request.id.clone(),
));
}
"ping" => {
return Some(method_not_found(
"Method not found: ping (removed in protocol 2026-07-28)",
request.id.clone(),
));
}
"notifications/initialized" => {
return Some(invalid_request(
"notifications/initialized must be sent as a notification (without 'id'), not as a request",
request.id.clone(),
));
}
"tools/list" => {
return handle_tools_list_shared(request.params.as_ref(), request.id.clone(), true);
}
"tools/call" => {
return handle_tools_call_shared(
request.params.as_ref(),
cancel_flag,
tool_semaphore,
request.id.clone(),
true,
)
.await;
}
"profiles/list" => {
return handle_profiles_list_shared(
request.params.as_ref(),
request.id.clone(),
true,
);
}
_ => {
let display_method = if request.method.len() > 100 {
let truncated = &request.method.as_bytes()[..100];
let mut end = truncated.len();
while end > 0 && !request.method.is_char_boundary(end) {
end -= 1;
}
format!("{}...", &request.method[..end])
} else {
request.method.clone()
};
return Some(method_not_found(
format!("Method not found: {}", display_method),
request.id.clone(),
));
}
}
}
if method == "initialize" {
let params = match request.params.as_ref() {
Some(p) => {
if !p.is_object() {
return Some(invalid_request(
"Invalid params: expected object",
request.id.clone(),
));
}
p
}
None => {
return Some(invalid_request(
"Invalid params: expected object",
request.id.clone(),
));
}
};
let init_params: InitializeParams = match serde_json::from_value(params.clone()) {
Ok(p) => p,
Err(e) => {
return Some(invalid_request(
format!("Invalid initialize params: {}", e),
request.id.clone(),
));
}
};
if init_params.client_info.name.is_empty() {
return Some(invalid_request(
"Invalid params: clientInfo.name is required and must not be empty",
request.id.clone(),
));
}
let negotiated_version = negotiate_legacy_version(&init_params.protocol_version);
let negotiated = NegotiatedProtocol {
version: negotiated_version.clone(),
client_name: init_params.client_info.name,
client_version: init_params.client_info.version,
client_capabilities: init_params.capabilities,
};
{
let mut state = session_state.lock().await;
if state.transition_to_awaiting(negotiated).is_err() {
return Some(already_initialized(request.id.clone()));
}
}
let result = InitializeResult {
protocol_version: negotiated_version.to_string(),
capabilities: build_server_capabilities(),
server_info: ServerInfo {
name: MCP_SERVER_NAME.to_string(),
version: env!("CARGO_PKG_VERSION").to_string(),
},
instructions: Some(SERVER_INSTRUCTIONS.to_string()),
};
return Some(serde_json::to_value(result).unwrap());
}
match method {
"ping" => Some(serde_json::json!({})),
"notifications/initialized" => {
Some(invalid_request(
"notifications/initialized must be sent as a notification (without 'id'), not as a request",
request.id.clone(),
))
}
_ => {
{
let state = session_state.lock().await;
if !state.allows_method(method) {
let err = match *state {
SessionState::Uninitialized | SessionState::AwaitingInitialized { .. } => {
not_initialized(method, request.id.clone())
}
SessionState::Ready { .. } => method_not_found(
format!("Method not found: {}", method),
request.id.clone(),
),
};
return Some(err);
}
}
match method {
"tools/list" => {
handle_tools_list_shared(request.params.as_ref(), request.id.clone(), false)
}
"tools/call" => {
handle_tools_call_shared(
request.params.as_ref(),
cancel_flag,
tool_semaphore,
request.id.clone(),
false,
)
.await
}
"profiles/list" => {
handle_profiles_list_shared(request.params.as_ref(), request.id.clone(), false)
}
_ => {
let display_method = if request.method.len() > 100 {
let truncated = &request.method.as_bytes()[..100];
let mut end = truncated.len();
while end > 0 && !request.method.is_char_boundary(end) {
end -= 1;
}
format!("{}...", &request.method[..end])
} else {
request.method.clone()
};
Some(method_not_found(
format!("Method not found: {}", display_method),
request.id.clone(),
))
}
}
}
}
}
pub async fn main() -> ! {
let stdin = tokio::io::stdin();
let mut reader = BufReader::new(stdin);
let tool_semaphore = Arc::new(tokio::sync::Semaphore::new(MAX_TOOL_WORKERS));
let active_requests = new_active_requests();
let session_state = Arc::new(Mutex::new(SessionState::Uninitialized));
let connection_era = Arc::new(Mutex::new(ConnectionEra::Undecided));
let (tx, mut rx) = tokio::sync::mpsc::channel::<Value>(64);
let writer_failed = Arc::new(std::sync::atomic::AtomicBool::new(false));
let writer_failed_task = writer_failed.clone();
let writer_handle = tokio::spawn(async move {
let mut scratch = Vec::new();
while let Some(response) = rx.recv().await {
if write_json_line(&response, &mut scratch).is_err() {
writer_failed_task.store(true, Ordering::Release);
break;
}
}
});
let mut join_set = tokio::task::JoinSet::new();
loop {
if writer_failed.load(Ordering::Acquire) {
break;
}
let line = match read_bounded_line(&mut reader, MAX_REQUEST_BYTES).await {
LimitedLine::Line(line) => line,
LimitedLine::TooLarge { observed_at_least } => {
let _ = tx
.send(json_rpc_error(
-32700,
format!(
"Request exceeds maximum size: at least {} bytes received, {} bytes maximum",
observed_at_least,
MAX_REQUEST_BYTES
),
None,
))
.await;
continue;
}
LimitedLine::Eof => break,
};
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
if trimmed.starts_with('[') {
let _ = tx
.send(invalid_request("Batch requests are not supported", None))
.await;
continue;
}
let request_value: serde_json::Value = match serde_json::from_str(trimmed) {
Ok(v) => v,
Err(_) => {
let _ = tx
.send(json_rpc_error(-32700, "Parse error: invalid JSON", None))
.await;
continue;
}
};
if !request_value.is_object() {
let _ = tx
.send(invalid_request(
"Invalid Request: expected JSON object",
None,
))
.await;
continue;
}
let actual_version = request_value
.get("jsonrpc")
.and_then(|v| v.as_str())
.unwrap_or("null");
if actual_version != "2.0" {
let _ = tx
.send(invalid_request(
format!(
"Invalid Request: jsonrpc must be '2.0', got '{}'",
actual_version
),
request_value.get("id").cloned(),
))
.await;
continue;
}
let method = match request_value.get("method") {
Some(Value::String(method)) => method.clone(),
Some(_) => {
let _ = tx
.send(invalid_request(
"Invalid Request: 'method' must be a string",
request_value.get("id").cloned(),
))
.await;
continue;
}
None => {
let _ = tx
.send(invalid_request(
"Invalid Request: missing 'method'",
request_value.get("id").cloned(),
))
.await;
continue;
}
};
let id = request_value.get("id");
if let Some(id_val) = id {
if id_val.is_boolean() || id_val.is_array() || id_val.is_object() {
let _ = tx
.send(invalid_request(
"Invalid Request: 'id' must be a string, integer, or null",
None,
))
.await;
continue;
}
if id_val.is_number() && id_val.as_i64().is_none() && id_val.as_u64().is_none() {
let _ = tx
.send(invalid_request(
"Invalid Request: 'id' must be a string, integer, or null",
None,
))
.await;
continue;
}
let id_str = id_val.to_string();
if id_str.len() > MAX_REQUEST_ID_LENGTH {
let _ = tx
.send(invalid_request(
format!(
"Invalid Request: 'id' exceeds maximum length of {}",
MAX_REQUEST_ID_LENGTH
),
None,
))
.await;
continue;
}
}
let request = JsonRpcRequest {
jsonrpc: "2.0".to_string(),
method,
params: request_value.get("params").cloned(),
id: id.cloned(),
};
if request.id.is_none() {
let classification =
classify_inbound_era(request.method.as_str(), request.params.as_ref());
let target_era = match &classification {
InboundEraClassification::Legacy => Some(ConnectionEra::Legacy),
InboundEraClassification::Modern20260728 => {
match parse_modern_request_meta(request.params.as_ref()) {
Some(Ok(_)) => Some(ConnectionEra::Modern20260728),
Some(Err(_)) | None => {
eprintln!(
"Warning: dropped notification with malformed modern envelope"
);
None
}
}
}
InboundEraClassification::InvalidModernEnvelope => {
eprintln!("Warning: dropped notification with malformed modern envelope");
None
}
InboundEraClassification::Unsupported { requested } => {
eprintln!(
"Warning: dropped notification claiming unsupported protocol revision {}",
requested
);
None
}
};
let Some(target_era) = target_era else {
continue;
};
if matches!(
pin_connection_era(&connection_era, target_era).await,
EraPinOutcome::Mismatch
) {
eprintln!(
"Warning: dropped {:?}-era notification on {:?}-pinned connection",
target_era,
current_connection_era(&connection_era).await
);
continue;
}
let modern_notification = target_era == ConnectionEra::Modern20260728;
match request.method.as_str() {
"notifications/initialized" => {
if !modern_notification {
let mut state = session_state.lock().await;
if let Err(e) = state.transition_to_ready() {
eprintln!(
"Warning: notifications/initialized ignored: {} (state: {:?})",
e, *state
);
}
}
}
"notifications/cancelled" => {
if let Some(params) = &request.params {
if let Some(request_id) = params.get("requestId") {
apply_cancellation(&active_requests, request_id).await;
} else {
eprintln!(
"Warning: notifications/cancelled missing 'requestId' parameter, ignoring"
);
}
} else {
eprintln!("Warning: notifications/cancelled missing 'params', ignoring");
}
}
_ => {
}
}
continue;
}
if request.id.as_ref().is_some_and(|v| v.is_null()) {
let _ = tx
.send(json_rpc_error(
-32600,
"Invalid Request: 'id' must not be null",
None,
))
.await;
continue;
}
let cancel_flag = Arc::new(std::sync::atomic::AtomicBool::new(false));
let request_id = request.id.clone().unwrap();
let (guard, registration) = match register_request(
&active_requests,
&cancel_flag,
request_id.clone(),
request.method.clone(),
)
.await
{
Ok(pair) => pair,
Err(RegisterRequestError::DuplicateId) => {
let _ = tx
.send(json_rpc_error(
-32600,
format!(
"Duplicate request id: {:?}",
truncate_id_display(&request_id)
),
request.id.clone(),
))
.await;
continue;
}
Err(RegisterRequestError::CapacityExceeded) => {
let _ = tx
.send(json_rpc_error_with_data(
-32000,
"Too many in-flight requests",
Some(serde_json::json!({
"code": "RESOURCE_EXHAUSTED",
"limit": crate::mcp::runtime::MAX_IN_FLIGHT_REQUESTS,
})),
request.id.clone(),
))
.await;
continue;
}
};
if request.method == "initialize" {
let result = handle_request_async(
&request,
&cancel_flag,
&tool_semaphore,
&session_state,
&connection_era,
)
.await;
complete_request(&active_requests, ®istration).await;
drop(guard);
if let Some(result) = result {
if result.get("error").is_some() && result.get("result").is_none() {
let _ = tx.send(result).await;
} else {
let response = JsonRpcResponse {
jsonrpc: "2.0".to_string(),
result,
id: Some(request_id),
};
if let Ok(value) = serde_json::to_value(response) {
let _ = tx.send(value).await;
}
}
}
continue;
}
let tx = tx.clone();
let semaphore_clone = tool_semaphore.clone();
let cancel_flag_clone = cancel_flag.clone();
let session_state_clone = session_state.clone();
let connection_era_clone = connection_era.clone();
let request_clone = request;
let request_id_for_response = request_id.clone();
let active_requests_clone = active_requests.clone();
let registration_clone = registration.clone();
join_set.spawn(async move {
let _active_guard = MetricGuard::new(&RUNTIME_METRICS.active_requests);
let inner = tokio::spawn(async move {
handle_request_async(
&request_clone,
&cancel_flag_clone,
&semaphore_clone,
&session_state_clone,
&connection_era_clone,
)
.await
});
let outcome = inner.await;
complete_request(&active_requests_clone, ®istration_clone).await;
drop(guard);
let maybe_result = outcome.unwrap_or_else(|e| {
Some(json_rpc_error(
-32000,
format!("Handler panic: {}", e),
Some(request_id_for_response.clone()),
))
});
if let Some(result) = maybe_result {
if result.get("error").is_some() && result.get("result").is_none() {
let _ = tx.send(result).await;
} else {
let response = JsonRpcResponse {
jsonrpc: "2.0".to_string(),
result,
id: Some(request_id_for_response),
};
if let Ok(value) = serde_json::to_value(response) {
let _ = tx.send(value).await;
}
}
}
});
}
while join_set.join_next().await.is_some() {}
drop(tx);
let _ = writer_handle.await;
let _ = std::io::stdout().flush();
std::process::exit(0);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mcp::compat::CompatibilityMode;
use crate::mcp::schema_validation::validate_property_inner;
use serde_json::json;
use std::collections::HashSet;
#[test]
fn tool_registration_tables_are_in_sync() {
let definitions = registry::mcp_tool_definitions();
let mut definition_names = HashSet::new();
for tool in &definitions {
assert!(
definition_names.insert(tool.name.as_str()),
"duplicate tool definition: {}",
tool.name
);
}
let registry_names = registry::tool_names();
for &name in ®istry_names {
assert!(
definition_names.contains(name),
"registry tool lacks definition: {name}"
);
assert!(
registry::tool_handler_for(name).is_some(),
"registry tool lacks handler: {name}"
);
}
for name in &definition_names {
assert!(
registry_names.contains(name),
"tool definition lacks registry entry: {name}"
);
}
assert_eq!(mcp_tool_count(), registry::tool_count());
}
#[test]
fn test_bug018_pattern_matches_anywhere_in_string() {
let schema = json!({"type": "string", "pattern": "[0-9]+"});
let result = validate_property_inner(
&json!("abc123"),
&schema,
"test",
10,
CompatibilityMode::EggcalcPython,
);
assert!(
result.is_none(),
"pattern [0-9]+ should match 'abc123' at position 3, got: {:?}",
result
);
}
#[test]
fn test_bug018_pattern_anchored_accepts() {
let schema = json!({"type": "string", "pattern": "^[A-Z]"});
let result = validate_property_inner(
&json!("Hello"),
&schema,
"test",
10,
CompatibilityMode::EggcalcPython,
);
assert!(
result.is_none(),
"pattern ^[A-Z] should match 'Hello', got: {:?}",
result
);
}
#[test]
fn test_bug018_pattern_anchored_rejects() {
let schema = json!({"type": "string", "pattern": "^[A-Z]"});
let result = validate_property_inner(
&json!("hello"),
&schema,
"test",
10,
CompatibilityMode::EggcalcPython,
);
assert!(result.is_some(), "pattern ^[A-Z] should reject 'hello'");
}
#[test]
fn test_bug018_pattern_no_match_rejects() {
let schema = json!({"type": "string", "pattern": "^[0-9]+$"});
let result = validate_property_inner(
&json!("abc123def"),
&schema,
"test",
10,
CompatibilityMode::EggcalcPython,
);
assert!(
result.is_some(),
"pattern ^[0-9]+$ should reject 'abc123def'"
);
}
#[test]
fn test_bug019_multipleof_relative_tolerance() {
let schema = json!({"type": "number", "multipleOf": 3.0});
let result = validate_property_inner(
&json!(9.000000001),
&schema,
"test",
10,
CompatibilityMode::EggcalcPython,
);
assert!(
result.is_none(),
"9.000000001 should pass multipleOf 3.0 with relative tolerance, got: {:?}",
result
);
}
#[test]
fn test_bug019_multipleof_exact_value() {
let schema = json!({"type": "number", "multipleOf": 5.0});
let result = validate_property_inner(
&json!(15.0),
&schema,
"test",
10,
CompatibilityMode::EggcalcPython,
);
assert!(
result.is_none(),
"15.0 should pass multipleOf 5.0, got: {:?}",
result
);
}
#[test]
fn test_bug019_multipleof_rejects_non_multiple() {
let schema = json!({"type": "number", "multipleOf": 3.0});
let result = validate_property_inner(
&json!(7.5),
&schema,
"test",
10,
CompatibilityMode::EggcalcPython,
);
assert!(result.is_some(), "7.5 should fail multipleOf 3.0");
}
#[test]
fn test_bug019_multipleof_large_value() {
let schema = json!({"type": "number", "multipleOf": 3.0});
let result = validate_property_inner(
&json!(3000000000.0),
&schema,
"test",
10,
CompatibilityMode::EggcalcPython,
);
assert!(
result.is_none(),
"3000000000.0 should pass multipleOf 3.0, got: {:?}",
result
);
}
}
#[cfg(test)]
mod truncate_utf8_bytes_tests {
use super::truncate_utf8_bytes;
#[test]
fn ascii_below_limit() {
assert_eq!(truncate_utf8_bytes("hello", 128, "..."), "hello");
}
#[test]
fn ascii_above_limit() {
let input = "a".repeat(200);
let result = truncate_utf8_bytes(&input, 128, "...");
assert!(result.len() <= 128 + 3);
assert!(result.ends_with("..."));
assert_eq!(&result[..125], "a".repeat(125).as_str());
}
#[test]
fn multibyte_cut_at_char_boundary() {
let input = "é".repeat(100); let result = truncate_utf8_bytes(&input, 128, "...");
assert!(result.len() <= 128 + 3);
assert!(result.ends_with("..."));
let content_len = result.len() - 3;
assert!(result[..content_len].is_char_boundary(content_len));
}
#[test]
fn multibyte_cut_inside_codepoint() {
let input = "é".repeat(100); let result = truncate_utf8_bytes(&input, 125, "...");
assert!(result.ends_with("..."));
assert_eq!(&result[..122], "é".repeat(61).as_str());
}
#[test]
fn mixed_ascii_and_multibyte() {
let mut input = "hello".to_string();
for _ in 0..50 {
input.push('é');
}
let result = truncate_utf8_bytes(&input, 50, "...");
assert!(result.len() <= 50 + 3);
assert!(result.ends_with("..."));
let content = &result[..result.len() - 3];
assert!(content.is_char_boundary(content.len()));
}
#[test]
fn zero_limit() {
assert_eq!(truncate_utf8_bytes("hello", 0, "..."), "...");
}
#[test]
fn suffix_larger_than_limit() {
assert_eq!(truncate_utf8_bytes("hello", 2, "..."), "...");
}
#[test]
fn truncate_id_display_with_unicode() {
use super::truncate_id_display;
use serde_json::json;
let long_id = json!("id-".to_string() + &"🎉".repeat(100));
let result = truncate_id_display(&long_id);
assert!(result.len() <= 128 + 3);
assert!(result.ends_with("..."));
}
#[test]
fn duplicate_unicode_id_produces_error_not_panic() {
use super::*;
use serde_json::json;
let long_unicode = json!("id-".to_string() + &"🎉".repeat(100));
let result = truncate_id_display(&long_unicode);
assert!(result.len() < 200);
}
#[tokio::test]
async fn bounded_line_short_lf() {
use super::*;
let data = b"hello world\n";
let mut cursor = std::io::Cursor::new(data);
let result = read_bounded_line(&mut cursor, 1000).await;
match result {
LimitedLine::Line(s) => assert_eq!(s, "hello world"),
_ => panic!("expected Line"),
}
}
#[tokio::test]
async fn bounded_line_short_crlf() {
use super::*;
let data = b"hello world\r\n";
let mut cursor = std::io::Cursor::new(data);
let result = read_bounded_line(&mut cursor, 1000).await;
match result {
LimitedLine::Line(s) => assert_eq!(s, "hello world"),
_ => panic!("expected Line"),
}
}
#[tokio::test]
async fn bounded_line_exactly_max_bytes() {
use super::*;
let payload = "x".repeat(100);
let data = format!("{}\n", payload);
let mut cursor = std::io::Cursor::new(data.as_bytes());
let result = read_bounded_line(&mut cursor, 100).await;
match result {
LimitedLine::Line(s) => assert_eq!(s, payload),
_ => panic!("expected Line for exactly max_bytes"),
}
}
#[tokio::test]
async fn bounded_line_one_over_max_rejected() {
use super::*;
let payload = "x".repeat(101);
let data = format!("{}\n", payload);
let mut cursor = std::io::Cursor::new(data.as_bytes());
let result = read_bounded_line(&mut cursor, 100).await;
match result {
LimitedLine::TooLarge { observed_at_least } => {
assert!(observed_at_least >= 100);
}
_ => panic!("expected TooLarge for limit+1"),
}
}
#[tokio::test]
async fn bounded_line_unterminated_large_input() {
use super::*;
let payload = "x".repeat(5 * 1024 * 1024);
let mut cursor = std::io::Cursor::new(payload.as_bytes());
let result = read_bounded_line(&mut cursor, 1_000_000).await;
match result {
LimitedLine::TooLarge { observed_at_least } => {
assert!(observed_at_least >= 1_000_000);
}
_ => panic!("expected TooLarge for multi-MB unterminated input"),
}
}
#[tokio::test]
async fn bounded_line_oversized_then_valid() {
use super::*;
let big = "a".repeat(200);
let data = format!("{}\nshort\n", big);
let mut cursor = std::io::Cursor::new(data.as_bytes());
let r1 = read_bounded_line(&mut cursor, 100).await;
assert!(matches!(r1, LimitedLine::TooLarge { .. }));
let r2 = read_bounded_line(&mut cursor, 100).await;
match r2 {
LimitedLine::Line(s) => assert_eq!(s, "short"),
_ => panic!("expected Line for second request"),
}
}
#[tokio::test]
async fn bounded_line_eof_after_final_non_newline() {
use super::*;
let data = b"no-newline-at-end";
let mut cursor = std::io::Cursor::new(data);
let result = read_bounded_line(&mut cursor, 1000).await;
match result {
LimitedLine::Line(s) => assert_eq!(s, "no-newline-at-end"),
_ => panic!("expected Line for EOF-terminated final line"),
}
}
#[tokio::test]
async fn bounded_line_empty_lines_ignored() {
use super::*;
let data = b"\n";
let mut cursor = std::io::Cursor::new(data);
let result = read_bounded_line(&mut cursor, 1000).await;
match result {
LimitedLine::Line(s) => assert_eq!(s, ""),
_ => panic!("expected Line for empty line"),
}
}
#[tokio::test]
async fn bounded_line_clean_eof() {
use super::*;
let data = b"";
let mut cursor = std::io::Cursor::new(data);
let result = read_bounded_line(&mut cursor, 1000).await;
assert!(matches!(result, LimitedLine::Eof));
}
struct FailingAfterData {
data: Vec<u8>,
pos: usize,
chunk: usize,
}
impl tokio::io::AsyncRead for FailingAfterData {
fn poll_read(
mut self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> std::task::Poll<std::io::Result<()>> {
if self.pos >= self.data.len() {
return std::task::Poll::Ready(Err(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
"simulated mid-line failure",
)));
}
let end = (self.pos + self.chunk).min(self.data.len());
buf.put_slice(&self.data[self.pos..end]);
self.pos = end;
std::task::Poll::Ready(Ok(()))
}
}
impl tokio::io::AsyncBufRead for FailingAfterData {
fn poll_fill_buf(
self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<&[u8]>> {
let this = self.get_mut();
if this.pos >= this.data.len() {
return std::task::Poll::Ready(Err(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
"simulated mid-line failure",
)));
}
let end = (this.pos + this.chunk).min(this.data.len());
std::task::Poll::Ready(Ok(&this.data[this.pos..end]))
}
fn consume(mut self: std::pin::Pin<&mut Self>, amt: usize) {
self.pos = (self.pos + amt).min(self.data.len());
}
}
#[tokio::test]
async fn bounded_line_midline_io_error_not_surfaced_as_line() {
use super::*;
let mut reader = FailingAfterData {
data: b"partial".to_vec(),
pos: 0,
chunk: 3,
};
let result = read_bounded_line(&mut reader, 1000).await;
assert!(
matches!(result, LimitedLine::Eof),
"mid-line I/O error must stop input processing, got {:?}",
result
);
}
#[tokio::test]
async fn bounded_line_oversized_payload_then_later_crlf_preserves_next_frame() {
use super::*;
let data = b"xxxYYY\r\nnext\n";
let mut reader = buffered_cursor(data, 3);
let first = read_bounded_line(&mut reader, 3).await;
assert!(matches!(first, LimitedLine::TooLarge { .. }));
let second = read_bounded_line(&mut reader, 100).await;
match second {
LimitedLine::Line(s) => assert_eq!(s, "next"),
other => panic!("expected preserved next frame, got {:?}", other),
}
}
use tokio::io::BufReader;
fn buffered_cursor(data: &[u8], cap: usize) -> BufReader<std::io::Cursor<Vec<u8>>> {
BufReader::with_capacity(cap, std::io::Cursor::new(data.to_vec()))
}
#[tokio::test]
async fn bounded_line_exactly_cap_lf_in_next_chunk() {
use super::*;
let payload = "x".repeat(100);
let data = format!("{}\nfollow", payload);
let mut reader = buffered_cursor(data.as_bytes(), 16);
let result = read_bounded_line(&mut reader, 100).await;
match result {
LimitedLine::Line(s) => assert_eq!(s, payload),
other => panic!("expected Line for exactly cap+LF, got {:?}", other),
}
}
#[tokio::test]
async fn bounded_line_exactly_cap_crlf_split_across_chunks() {
use super::*;
let payload = "x".repeat(3);
let data = format!("{}\r\n", payload);
let mut reader = buffered_cursor(data.as_bytes(), 4);
let result = read_bounded_line(&mut reader, 3).await;
match result {
LimitedLine::Line(s) => assert_eq!(s, payload),
other => panic!("expected Line for exactly cap+CRLF, got {:?}", other),
}
}
#[tokio::test]
async fn bounded_line_exactly_cap_eof_terminated() {
use super::*;
let payload = "x".repeat(100);
let mut reader = buffered_cursor(payload.as_bytes(), 16);
let result = read_bounded_line(&mut reader, 100).await;
match result {
LimitedLine::Line(s) => assert_eq!(s, payload),
other => panic!("expected Line for cap+EOF, got {:?}", other),
}
}
#[tokio::test]
async fn bounded_line_cap_plus_one_payload_rejected() {
use super::*;
let payload = "x".repeat(101);
let data = format!("{}\n", payload);
let mut reader = buffered_cursor(data.as_bytes(), 16);
let result = read_bounded_line(&mut reader, 100).await;
assert!(
matches!(result, LimitedLine::TooLarge { .. }),
"expected TooLarge for cap+1 payload, got {:?}",
result
);
let next = read_bounded_line(&mut reader, 1000).await;
assert!(matches!(next, LimitedLine::Eof));
}
#[tokio::test]
async fn bounded_line_cap_plus_one_crlf_rejected_across_chunks() {
use super::*;
let payload = "x".repeat(4);
let data = format!("{}\r\nfollow\n", payload);
let mut reader = buffered_cursor(data.as_bytes(), 4);
let first = read_bounded_line(&mut reader, 3).await;
assert!(matches!(first, LimitedLine::TooLarge { .. }));
let second = read_bounded_line(&mut reader, 100).await;
assert!(matches!(second, LimitedLine::Line(s) if s == "follow"));
}
#[tokio::test]
async fn bounded_line_oversized_crlf_then_multiple_valid_frames() {
use super::*;
let data = b"xxxxxx\r\nfirst\nsecond\r\n";
let mut reader = buffered_cursor(data, 3);
assert!(matches!(
read_bounded_line(&mut reader, 3).await,
LimitedLine::TooLarge { .. }
));
assert!(matches!(
read_bounded_line(&mut reader, 100).await,
LimitedLine::Line(s) if s == "first"
));
assert!(matches!(
read_bounded_line(&mut reader, 100).await,
LimitedLine::Line(s) if s == "second"
));
}
#[tokio::test]
async fn bounded_line_cap_plus_one_eof_rejected() {
use super::*;
let payload = "x".repeat(4);
let mut reader = buffered_cursor(payload.as_bytes(), 2);
assert!(matches!(
read_bounded_line(&mut reader, 3).await,
LimitedLine::TooLarge { .. }
));
}
#[tokio::test]
async fn bounded_line_oversized_then_valid_preserves_next_frame() {
use super::*;
let big = "a".repeat(200);
let data = format!("{}\nshort\n", big);
let mut reader = buffered_cursor(data.as_bytes(), 8);
let r1 = read_bounded_line(&mut reader, 100).await;
assert!(matches!(r1, LimitedLine::TooLarge { .. }));
let r2 = read_bounded_line(&mut reader, 100).await;
match r2 {
LimitedLine::Line(s) => assert_eq!(s, "short"),
other => panic!("expected Line for second request, got {:?}", other),
}
}
#[tokio::test]
async fn bounded_line_oversized_then_two_valid_preserved() {
use super::*;
let big = "a".repeat(200);
let data = format!("{}\nfirst\nsecond\n", big);
let mut reader = buffered_cursor(data.as_bytes(), 8);
let r1 = read_bounded_line(&mut reader, 100).await;
assert!(matches!(r1, LimitedLine::TooLarge { .. }));
let r2 = read_bounded_line(&mut reader, 100).await;
let r3 = read_bounded_line(&mut reader, 100).await;
match (r2, r3) {
(LimitedLine::Line(a), LimitedLine::Line(b)) => {
assert_eq!(a, "first");
assert_eq!(b, "second");
}
other => panic!("expected two Lines, got {:?}", other),
}
}
#[tokio::test]
async fn bounded_line_unterminated_oversized_does_not_consume_next() {
use super::*;
let payload = "x".repeat(64 * 1024);
let data = format!("{}\nfollow\n", payload);
let mut reader = buffered_cursor(data.as_bytes(), 16);
let r1 = read_bounded_line(&mut reader, 100).await;
assert!(matches!(r1, LimitedLine::TooLarge { .. }));
let r2 = read_bounded_line(&mut reader, 100).await;
match r2 {
LimitedLine::Line(s) => assert_eq!(s, "follow"),
other => panic!("expected Line for follow-up, got {:?}", other),
}
}
#[tokio::test]
async fn bounded_line_cap_reached_with_oversized_chunk_in_next_fill() {
use super::*;
let prefix = "a".repeat(90);
let mid = "b".repeat(20);
let data = format!("{}{}\nfollow\n", prefix, mid);
let mut reader = buffered_cursor(data.as_bytes(), data.len());
let r1 = read_bounded_line(&mut reader, 100).await;
assert!(matches!(r1, LimitedLine::TooLarge { .. }));
let r2 = read_bounded_line(&mut reader, 100).await;
match r2 {
LimitedLine::Line(s) => assert_eq!(s, "follow"),
other => panic!("expected Line for follow-up, got {:?}", other),
}
}
}