use std::sync::Arc;
use std::time::Duration;
use rmcp::ErrorData;
use serde_json::Value;
use crate::server::helpers::get_str;
use crate::server::tool_trait::{McpTool, ShellOutcome, ToolContext, ToolOutput};
use crate::tools::LeanCtxServer;
use rmcp::model::ContentBlock;
impl LeanCtxServer {
pub(super) async fn dispatch_tool(
&self,
name: &str,
args: Option<&serde_json::Map<String, Value>>,
minimal: bool,
) -> Result<
(
String,
usize,
Option<ShellOutcome>,
Option<Vec<ContentBlock>>,
),
ErrorData,
> {
fn format_rate_limited(
tool: &str,
agent_id: &str,
retry_after_ms: u64,
args: Option<&serde_json::Map<String, Value>>,
) -> String {
let as_json = get_str(args, "format").as_deref() == Some("json");
if as_json {
serde_json::json!({
"error": "rate_limited",
"tool": tool,
"agent_id": agent_id,
"retry_after_ms": retry_after_ms,
})
.to_string()
} else {
format!("[RATE LIMITED] tool={tool} retry_after_ms={retry_after_ms}")
}
}
let host_hook = crate::server::dynamic_tools::targets_internal_host_tool(name, args);
let refuse = |text: String| {
if host_hook {
Err(ErrorData::invalid_request(text, None))
} else {
Ok((text, 0, None, None))
}
};
if let Some(line) = crate::server::dynamic_tools::withheld_cloud_tool_refusal(name, args) {
return Ok((line.to_owned(), 0, None, None));
}
let agent_id = self
.agent_id
.read()
.await
.clone()
.unwrap_or_else(|| "unknown".to_string());
{
if let lean_ctx::core::a2a::rate_limiter::RateLimitResult::Limited { retry_after_ms } =
lean_ctx::core::a2a::rate_limiter::check_rate_limit(&agent_id, name)
{
return refuse(format_rate_limited(name, &agent_id, retry_after_ms, args));
}
}
if name.starts_with("ctx_") {
crate::server::tool_visibility::mark_auto_ctx_tool_used();
}
if lean_ctx_cloud::metrics_v2::signals::recording() {
let client = self.client_name.read().await.clone();
lean_ctx_cloud::metrics_v2::signals::host_call(&client);
}
let _activity = lean_ctx::core::graph_enricher::ToolActivity::begin();
match name {
"ctx_call" => {
let (inner, arg_map) = crate::tools::registered::ctx_call::resolve_inner(args)?;
if let lean_ctx::core::a2a::rate_limiter::RateLimitResult::Limited {
retry_after_ms,
} = lean_ctx::core::a2a::rate_limiter::check_rate_limit(&agent_id, &inner)
{
return refuse(format_rate_limited(
&inner,
&agent_id,
retry_after_ms,
arg_map.as_ref(),
));
}
let inner_role_check = crate::server::role_guard::check_tool_access(&inner);
if let Some(denied) =
crate::server::role_guard::into_call_tool_result(&inner_role_check)
{
let msg = denied
.content
.first()
.and_then(|c| c.as_text())
.map_or_else(|| "Blocked by role policy".to_string(), |t| t.text.clone());
return refuse(msg);
}
let active = self.workflow.read().await.clone();
if let Some(run) = active {
use lean_ctx::core::workflow::ToolGate;
match lean_ctx::core::workflow::tool_gate(
&run,
&inner,
super::WORKFLOW_PASSTHROUGH_TOOLS,
) {
ToolGate::Pass => {}
ToolGate::Expired => {
let mut wf = self.workflow.write().await;
*wf = None;
let _ = lean_ctx::core::workflow::clear_active();
}
ToolGate::Refuse(reason) => return refuse(reason),
}
}
let result = self
.dispatch_inner(&inner, arg_map.as_ref(), minimal)
.await?;
Ok(result)
}
_ => self.dispatch_inner(name, args, minimal).await,
}
}
async fn dispatch_inner(
&self,
name: &str,
args: Option<&serde_json::Map<String, Value>>,
minimal: bool,
) -> Result<
(
String,
usize,
Option<ShellOutcome>,
Option<Vec<ContentBlock>>,
),
ErrorData,
> {
if lean_ctx::core::config::Config::load().edit_tool_blocked(name) {
return Ok((
format!(
"[disabled] '{name}' is turned off (prefer_native_editor): use your editor's \
built-in edit tool. Re-enable with `lean-ctx config set prefer_native_editor false`."
),
0,
None,
None,
));
}
if crate::server::dynamic_tools::is_withheld_cloud_tool(name) {
return Ok((lean_ctx_cloud::TOOL_NOT_AVAILABLE.to_owned(), 0, None, None));
}
if name == "ctx_tasks" && self.session_mode == crate::tools::SessionMode::Shared {
return Ok((
"[unavailable] ctx_tasks works only in a personal MCP session: a shared \
server cannot bind a task claim to the client that calls it."
.to_owned(),
0,
None,
None,
));
}
if let Some(tool) = self.registry.as_ref().and_then(|r| r.get_arc(name)) {
let empty = serde_json::Map::new();
let args_map = args.unwrap_or(&empty);
let aliased = canonicalize_arg_aliases(tool.as_ref(), args_map);
let args_map = aliased.as_ref().unwrap_or(args_map);
let project_root = {
let session = self.session.read().await;
session.project_root.clone().unwrap_or_default()
};
let authority = lean_ctx::core::workspace_authority::current();
let may_index = lean_ctx::core::workspace_authority::root_authorized(
std::path::Path::new(&project_root),
);
if may_index
&& !project_root.is_empty()
&& lean_ctx::core::index_orchestrator::ensure_warm_for_tool(&project_root, name)
{
let extra_roots = match authority.snapshot() {
Some(snapshot) => snapshot.additional_root_strings(),
None => self.session.read().await.extra_roots.clone(),
};
if !extra_roots.is_empty() {
let primary = project_root.clone();
std::thread::spawn(move || {
lean_ctx::core::index_orchestrator::ensure_extra_roots_background(
&primary,
&extra_roots,
);
});
}
}
let mut resolved_paths = std::collections::HashMap::new();
let mut path_errors: std::collections::HashMap<String, String> =
std::collections::HashMap::new();
for key in PATH_LIKE_KEYS {
if let Some(val) = args_map.get(*key) {
if let Some(raw) = val.as_str() {
match self.resolve_path_for_tool(raw, name).await {
Ok(resolved) => {
if !["path", "project_root", "root"].contains(key) {
tracing::trace!(
"[pathjail] resolved non-standard path key '{key}': {raw} -> {resolved}"
);
}
resolved_paths.insert(key.to_string(), resolved);
}
Err(refusal) => {
tracing::debug!(
"[dispatch] path resolution failed for '{key}' = '{raw}': {}",
refusal.message
);
self.record_path_refusal(name, &refusal).await;
path_errors.insert(key.to_string(), refusal.message);
}
}
} else {
let type_name = match val {
serde_json::Value::Number(_) => "number",
serde_json::Value::Bool(_) => "boolean",
serde_json::Value::Array(_) => "array",
serde_json::Value::Object(_) => "object",
serde_json::Value::Null => "null",
serde_json::Value::String(_) => unreachable!(),
};
path_errors.insert(
key.to_string(),
format!("{key} must be a string, got {type_name}"),
);
}
}
}
let crp_mode = crate::tools::CrpMode::effective();
let (project_root, extra_roots) = {
let session = self.session.read().await;
(
session.project_root.clone().unwrap_or_default(),
session.extra_roots.clone(),
)
};
let (project_root, extra_roots) = match authority.snapshot() {
Some(snapshot) => {
let root = snapshot.project_root_for(&project_root);
let extra = snapshot
.granting_roots()
.map(|(path, _)| path.to_string_lossy().into_owned())
.filter(|path| *path != root)
.collect();
(root, extra)
}
None if authority.is_active() => (String::new(), Vec::new()),
None => (project_root, extra_roots),
};
let ctx = crate::server::tool_trait::ToolContext {
project_root,
extra_roots,
minimal,
resolved_paths,
crp_mode,
cache: Some(self.cache.clone()),
session: Some(self.session.instance()),
tool_calls: Some(self.tool_calls.clone()),
agent_id: Some(self.agent_id.clone()),
workflow: Some(self.workflow.clone()),
ledger: Some(self.ledger.clone()),
client_name: Some(self.client_name.clone()),
client_role: None,
shell_access: None,
pipeline_stats: Some(self.pipeline_stats.clone()),
call_count: Some(self.call_count.clone()),
autonomy: Some(self.autonomy.clone()),
path_errors,
bm25_cache: Some(self.bm25_cache.clone()),
progress_sender: Some(self.progress_sender.clone()),
cancel: crate::server::tool_trait::REQUEST_CT
.try_with(tokio_util::sync::CancellationToken::clone)
.ok(),
};
let provider_snapshot =
name == "ctx_provider" && crate::tools::ctx_provider::is_snapshot_request(args_map);
let handler_started = std::time::Instant::now();
let (output, observed_origin) = lean_ctx::core::archive::authority::capture(
self.run_tool_handler(name, tool, args_map, ctx),
)
.await;
let output = output?;
if let Some(admissions) = lean_ctx::core::context_admission::capture::current() {
admissions.set_original_tokens(output.original_tokens as u64);
}
let file_output = name == "ctx_execute"
&& args_map.get("action").and_then(Value::as_str) == Some("file")
&& matches!(output.shell_outcome, Some(ShellOutcome::Exit(0)));
if let Some(origin) = &observed_origin {
origin.clone().publish();
}
let output_origin = observed_origin.filter(|_| file_output);
let handler_ms = handler_started.elapsed().as_millis() as u64;
if output.content_blocks.is_some() {
if let Some(ref path) = output.path {
self.record_call_with_path(
name,
0,
0,
Some("image".to_string()),
Some(path),
handler_ms,
)
.await;
} else {
self.record_call_with_timing(name, 0, 0, Some("image".to_string()), handler_ms)
.await;
}
return Ok((
String::new(),
0,
output.shell_outcome,
output.content_blocks,
));
}
let config_changed =
super::tools_config_watch::has_changed(&self.last_tools_config_hash);
if (output.changed || config_changed)
&& let Some(peer) = self.peer.read().await.as_ref()
{
if config_changed {
tracing::info!(
"Tool-config changed (profile/enabled/disabled) — sending tools/list_changed"
);
}
super::notifications::send_tools_list_changed(peer).await;
}
let headers_only =
lean_ctx::core::config::ResponseVerbosity::effective().is_headers_only();
let header_line = if headers_only && !provider_snapshot {
Some(output.to_header_line(name))
} else {
None
};
let output_token_estimate = lean_ctx::core::tokens::count_tokens(&output.text) as u32;
if let Some(ref path) = output.path {
{
if name != "ctx_read" {
let sent_tokens = if output.original_tokens > 0 {
output.original_tokens.saturating_sub(output.saved_tokens)
} else {
lean_ctx::core::tokens::count_tokens(&output.text)
};
let orig = if output.original_tokens > 0 {
output.original_tokens
} else {
sent_tokens
};
let mode_str = output.mode.as_deref().unwrap_or("full");
let mut ledger = self.ledger.write().await;
ledger.record(path, mode_str, orig, sent_tokens);
ledger.save_debounced();
}
}
self.record_call_with_path(
name,
output.original_tokens,
output.saved_tokens,
output.mode,
Some(path),
handler_ms,
)
.await;
} else {
self.record_call_with_timing(
name,
output.original_tokens,
output.saved_tokens,
output.mode,
handler_ms,
)
.await;
}
let agent_id = self
.agent_id
.read()
.await
.clone()
.unwrap_or_else(|| "unknown".into());
let role = lean_ctx::core::roles::active_role_name();
{
use lean_ctx::core::audit_trail as audit;
let input_hash = audit::keyed_input_digest(args_map)
.unwrap_or_else(|| audit::hash_input(args_map));
let data = audit::AuditEntryData {
agent_id: agent_id.clone(),
tool: name.to_string(),
action: None,
input_hash,
output_tokens: output_token_estimate,
role: role.clone(),
event_type: audit::AuditEventType::ToolCall,
};
let session_id = self.session.read().await.id.clone();
if session_id.is_empty() {
audit::record(data);
} else {
audit::record_v2(
data,
audit::SessionFacts {
session_id,
instance_id: None,
policy_digest: None,
decision: audit::AuditDecision::Allow,
output_digest: audit::keyed_digest("output", output.text.as_bytes()),
},
);
}
}
let saved = output.saved_tokens;
let raw_text = header_line.unwrap_or(output.text);
let final_text = if provider_snapshot {
raw_text
} else {
sanitized_tool_text(name, raw_text)
};
let output_kind = lean_ctx::core::output_sanitizer::ContentKind::of(
&final_text,
output.path.as_deref().map(std::path::Path::new),
);
let injection_signals =
lean_ctx::core::output_sanitizer::detect_injection_as(&final_text, output_kind);
let gateway_flagged = lean_ctx::core::context_admission::capture::current()
.is_some_and(|admissions| admissions.flagged_injection());
if !injection_signals.is_empty() && !gateway_flagged {
tracing::warn!(
tool = name,
lines = injection_signals.len(),
"prompt-injection patterns detected in tool output"
);
let flag = lean_ctx::core::security_events::InjectionFlag {
object_sha256: {
use sha2::Digest as _;
lean_ctx::core::agent_identity::hex_encode(&sha2::Sha256::digest(
final_text.as_bytes(),
))
},
patterns: lean_ctx::core::output_sanitizer::InjectionCategory::mask(
&injection_signals,
),
};
if lean_ctx::core::security_events::record_injections(name, &agent_id, &[flag]) > 0
{
self.publish_value_snapshot().await;
}
}
let reference_enabled = std::env::var("LEAN_CTX_REFERENCE_RESULTS").map_or_else(
|_| lean_ctx::core::config::Config::load().reference_results,
|v| v == "1" || v == "true",
);
if reference_enabled
&& !provider_snapshot
&& !lean_ctx::core::firewall::is_protected_read(name)
&& !output.shell_outcome.as_ref().is_some_and(
crate::server::tool_trait::ShellOutcome::is_terminal_background_status,
)
&& final_text.len() > REFERENCE_THRESHOLD
&& let Some(ref_id) = super::reference_store::store_with_authority(
&final_text,
output_origin.as_ref(),
)
{
let mut preview_end = final_text.len().min(200);
while preview_end > 0 && !final_text.is_char_boundary(preview_end) {
preview_end -= 1;
}
let resolve = if output_origin.is_some() {
format!("ctx_expand(id=\"{ref_id}\")")
} else {
format!("/v1/references/{ref_id}")
};
let summary = format!(
"[Reference: {ref_id}] Output stored ({} chars, ~{} tokens). Resolve: {resolve}\nPreview: {}...",
final_text.len(),
final_text.len() / 4,
&final_text[..preview_end]
);
return Ok((summary, saved, output.shell_outcome, None));
}
return Ok((final_text, saved, output.shell_outcome, None));
}
if let Some(message) = crate::server::dynamic_tools::removed_tool_message(name) {
return Err(ErrorData::new(
rmcp::model::ErrorCode::METHOD_NOT_FOUND,
message,
None,
));
}
let suggestion = self
.registry
.as_ref()
.and_then(|r| {
let names = r
.names()
.into_iter()
.filter(|n| !crate::server::dynamic_tools::is_withheld_cloud_tool(n));
lean_ctx::core::levenshtein::closest(name, names)
})
.map(|s| format!(" — did you mean '{s}'?"))
.unwrap_or_default();
Err(ErrorData::new(
rmcp::model::ErrorCode::METHOD_NOT_FOUND,
format!("Unknown tool: {name}{suggestion}"),
None,
))
}
async fn run_tool_handler(
&self,
name: &str,
tool: Arc<dyn McpTool>,
args_map: &serde_json::Map<String, Value>,
ctx: ToolContext,
) -> Result<ToolOutput, ErrorData> {
let watchdog = Self::handler_watchdog_for(name, args_map);
let args_owned = args_map.clone();
let tool_name = name.to_string();
let agent_id = self
.agent_id
.read()
.await
.clone()
.unwrap_or_else(|| "unknown".to_string());
let handoff = lean_ctx::core::context_kernel::bridge::runtime::current_handoff();
let task = lean_ctx::core::task_spine::TaskSpine::current();
let receipt_capture = crate::server::native_receipts::current_capture();
let archive_capture = lean_ctx::core::archive::authority::current_capture();
let admissions = lean_ctx::core::context_admission::capture::current();
let presenter = lean_ctx::core::archive::presented::request_presenter();
let caller = ctx.session.clone();
let workspace = lean_ctx::core::workspace_authority::current();
let session_rights = lean_ctx::core::session_rights::current();
let shell_grant = crate::server::shell_approval::current_grant();
let write_roots: Vec<String> = std::iter::once(ctx.project_root.clone())
.chain(ctx.extra_roots.iter().cloned())
.collect();
let policy_project = lean_ctx::core::policy::runtime::REQUEST_PROJECT
.try_with(|slot| slot.borrow().clone())
.ok()
.flatten()
.or_else(|| {
(!ctx.project_root.is_empty()).then(|| std::path::PathBuf::from(&ctx.project_root))
});
let join = tokio::task::spawn_blocking(move || {
let handle = || {
lean_ctx::core::archive::authority::CAPTURE.sync_scope(archive_capture, || {
lean_ctx::core::task_spine::TaskSpine::sync_scope(task, || {
crate::server::native_receipts::NATIVE_RECEIPT_CAPTURE.sync_scope(
receipt_capture,
|| {
lean_ctx::core::policy::runtime::REQUEST_PROJECT.sync_scope(
std::cell::RefCell::new(policy_project),
|| {
lean_ctx::core::context_kernel::bridge::runtime::KERNEL_PLANNING_HANDOFF
.sync_scope(handoff, || {
lean_ctx::core::context_admission::capture::ADMISSIONS
.sync_scope(admissions, || {
lean_ctx::core::archive::presented::with_presenter(
presenter,
|| {
lean_ctx::core::pathjail_scope::with_request_write_roots(
&write_roots,
|| {
lean_ctx::core::session::caller::scope(
caller.clone(),
|| {
lean_ctx::core::workspace_authority::sync_scope(
workspace.clone(),
|| {
crate::server::shell_approval::SHELL_GRANT
.sync_scope(shell_grant.clone(), || {
tool.handle(&args_owned, &ctx)
})
},
)
},
)
},
)
},
)
})
})
},
)
},
)
})
})
};
let (result, tally) = lean_ctx::core::security_events::collect_call(|| {
lean_ctx::core::session_rights::sync_scope(session_rights, handle)
});
lean_ctx::core::security_events::record_call(&tool_name, &agent_id, &tally);
result
});
Self::watchdog_join(name, join, watchdog).await
}
fn handler_watchdog_for(name: &str, args: &serde_json::Map<String, Value>) -> Option<Duration> {
let base = Self::handler_watchdog(name)?;
if name == "ctx_agent" && args.get("action").and_then(Value::as_str) == Some("wait") {
let secs = args
.get("timeout_secs")
.and_then(Value::as_u64)
.unwrap_or(crate::tools::ctx_agent::WAIT_DEFAULT_SECS)
.min(crate::tools::ctx_agent::WAIT_MAX_SECS);
return Some(base.max(Duration::from_secs(secs + 30)));
}
Some(base)
}
async fn watchdog_join(
name: &str,
join: tokio::task::JoinHandle<Result<ToolOutput, ErrorData>>,
watchdog: Option<Duration>,
) -> Result<ToolOutput, ErrorData> {
let Some(limit) = watchdog else {
return Self::unwrap_join(name, join.await);
};
tokio::select! {
joined = join => Self::unwrap_join(name, joined),
() = tokio::time::sleep(limit) => {
lean_ctx::core::io_health::record_freeze();
tracing::error!(
tool = name,
timeout_secs = limit.as_secs(),
"tool watchdog fired — handler cancelled to reclaim pool slot (#1018)"
);
Err(ErrorData::internal_error(
format!(
"tool '{name}' exceeded its {}s watchdog and was abandoned. \
The MCP server is still running — retry or narrow the request.",
limit.as_secs()
),
None,
))
}
}
}
fn unwrap_join(
name: &str,
joined: Result<Result<ToolOutput, ErrorData>, tokio::task::JoinError>,
) -> Result<ToolOutput, ErrorData> {
match joined {
Ok(inner) => inner,
Err(join_err) => {
tracing::error!(
tool = name,
is_panic = join_err.is_panic(),
"tool handler did not complete (panic isolated on the blocking pool)"
);
Err(ErrorData::internal_error(
format!(
"tool '{name}' failed unexpectedly. The MCP server is still running \
— retry or use a different approach."
),
None,
))
}
}
}
fn handler_watchdog(name: &str) -> Option<Duration> {
if super::is_shell_tool_name(name) {
return None;
}
watchdog_from_secs(read_watchdog_secs())
}
}
fn sanitized_tool_text(name: &str, raw_text: String) -> String {
if lean_ctx::core::firewall::is_protected_read(name) {
return raw_text;
}
lean_ctx::core::output_sanitizer::sanitize(&raw_text)
}
fn read_watchdog_secs() -> u64 {
std::env::var("LEAN_CTX_TOOL_TIMEOUT_SECS")
.ok()
.and_then(|v| v.parse::<u64>().ok())
.unwrap_or(DEFAULT_TOOL_TIMEOUT_SECS)
}
fn watchdog_from_secs(secs: u64) -> Option<Duration> {
(secs > 0).then(|| Duration::from_secs(secs))
}
const REFERENCE_THRESHOLD: usize = 4000;
const DEFAULT_TOOL_TIMEOUT_SECS: u64 = 120;
use super::tool_trait::PATH_LIKE_KEYS;
const ARG_ALIASES: &[(&str, &[&str])] = &[
("path", &["file_path", "filePath", "file", "filename"]),
("command", &["cmd"]),
];
pub fn canonicalize_arg_aliases(
tool: &dyn McpTool,
args: &serde_json::Map<String, Value>,
) -> Option<serde_json::Map<String, Value>> {
let pending: Vec<(&str, &str)> = ARG_ALIASES
.iter()
.filter(|(canonical, _)| !args.contains_key(*canonical))
.filter_map(|(canonical, aliases)| {
aliases
.iter()
.find(|alias| args.get(**alias).is_some_and(Value::is_string))
.map(|alias| (*canonical, *alias))
})
.collect();
if pending.is_empty() {
return None;
}
let def = tool.tool_def();
let declared = def
.input_schema
.get("properties")
.and_then(Value::as_object)?;
let mut out = args.clone();
let mut changed = false;
for (canonical, alias) in pending {
if declared.contains_key(canonical)
&& !declared.contains_key(alias)
&& let Some(value) = out.remove(alias)
{
out.insert(canonical.to_string(), value);
changed = true;
}
}
changed.then_some(out)
}
#[cfg(test)]
mod session_stats_tests;
#[cfg(test)]
mod alias_tests {
use super::*;
fn tool(name: &str) -> Arc<dyn McpTool> {
crate::server::registry::build_registry()
.get_arc(name)
.unwrap_or_else(|| panic!("{name} registered"))
}
fn map(v: Value) -> serde_json::Map<String, Value> {
match v {
Value::Object(m) => m,
other => panic!("expected an object, got {other}"),
}
}
#[test]
fn file_path_becomes_path_for_ctx_read() {
let out = canonicalize_arg_aliases(
tool("ctx_read").as_ref(),
&map(serde_json::json!({"file_path": "src/main.rs", "mode": "map"})),
)
.expect("alias renamed");
assert_eq!(out.get("path").and_then(Value::as_str), Some("src/main.rs"));
assert!(!out.contains_key("file_path"));
}
#[test]
fn cmd_becomes_command_for_ctx_shell() {
let out = canonicalize_arg_aliases(
tool("ctx_shell").as_ref(),
&map(serde_json::json!({"cmd": "git status"})),
)
.expect("alias renamed");
assert_eq!(
out.get("command").and_then(Value::as_str),
Some("git status")
);
}
#[test]
fn declared_alias_and_explicit_canonical_are_untouched() {
assert!(
canonicalize_arg_aliases(
tool("ctx_search").as_ref(),
&map(serde_json::json!({"pattern": "x", "file_path": "a.rs"})),
)
.is_none()
);
assert!(
canonicalize_arg_aliases(
tool("ctx_read").as_ref(),
&map(serde_json::json!({"path": "a.rs", "file_path": "b.rs"})),
)
.is_none()
);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn provider_snapshot_uses_normal_pipeline_and_token_accounting() {
let server = crate::tools::create_server();
let args = serde_json::json!({
"action": "query", "mode": "snapshot", "provider": "gitlab",
"resource": "merge_requests", "limit": 0
});
let (text, saved, _, blocks) = server
.dispatch_inner("ctx_provider", args.as_object(), false)
.await
.expect("bounded input error is a snapshot envelope");
assert!(
blocks.is_none(),
"snapshot must not bypass policy/budget/IR processing"
);
assert_eq!(saved, 0);
let parsed: Value = serde_json::from_str(&text).expect("unmodified JSON");
assert_eq!(parsed["schema_version"], 1);
assert!(parsed.get("error").is_some());
let calls = server.tool_calls.read().await;
let record = calls.last().expect("snapshot call recorded");
assert_eq!(record.mode.as_deref(), Some("snapshot"));
assert_eq!(
record.original_tokens,
lean_ctx::core::tokens::count_tokens(&text)
);
assert!(record.original_tokens > 0);
assert_eq!(record.saved_tokens, 0);
}
#[test]
fn protected_reads_bypass_the_degenerate_output_sanitizer() {
let fixture = "ok line\n!!!!!!!!!!!!\ntail\n".to_string();
assert_eq!(
sanitized_tool_text("ctx_read", fixture.clone()),
fixture,
"ctx_read must never lose file bytes to the flood filter"
);
let cleaned = sanitized_tool_text("ctx_shell", fixture);
assert!(
!cleaned.contains("!!!!!!!!!!"),
"flood line must be removed"
);
assert!(cleaned.contains("ok line") && cleaned.contains("tail"));
}
#[test]
fn path_like_keys_has_no_duplicates() {
let mut seen = std::collections::HashSet::new();
for key in PATH_LIKE_KEYS {
assert!(seen.insert(*key), "duplicate PATH_LIKE_KEYS entry: {key}");
}
}
#[test]
fn path_like_keys_includes_primary_keys() {
for primary in &["path", "project_root", "root"] {
assert!(
PATH_LIKE_KEYS.contains(primary),
"primary key '{primary}' missing from PATH_LIKE_KEYS"
);
}
}
#[test]
fn path_like_keys_all_non_empty() {
for key in PATH_LIKE_KEYS {
assert!(!key.is_empty(), "PATH_LIKE_KEYS contains empty string");
}
assert!(
PATH_LIKE_KEYS.len() >= 3,
"PATH_LIKE_KEYS must have at least the 3 primary keys"
);
}
#[test]
fn watchdog_disabled_for_long_running_shell_tools() {
assert!(
LeanCtxServer::handler_watchdog("ctx_shell").is_none(),
"ctx_shell runs arbitrary user commands and must not be watchdog-bounded"
);
assert!(
LeanCtxServer::handler_watchdog("ctx_execute").is_none(),
"ctx_execute must not be watchdog-bounded"
);
}
#[test]
fn ctx_agent_wait_outlives_the_default_watchdog_by_its_own_timeout() {
let args = |v: Value| v.as_object().cloned().unwrap();
if std::env::var_os("LEAN_CTX_TOOL_TIMEOUT_SECS").is_some() {
return;
}
let wait = LeanCtxServer::handler_watchdog_for(
"ctx_agent",
&args(serde_json::json!({"action": "wait", "timeout_secs": 900})),
);
assert_eq!(wait, Some(Duration::from_secs(930)));
let default_wait = LeanCtxServer::handler_watchdog_for(
"ctx_agent",
&args(serde_json::json!({"action": "wait"})),
);
assert_eq!(default_wait, Some(Duration::from_secs(630)));
let read = LeanCtxServer::handler_watchdog_for(
"ctx_agent",
&args(serde_json::json!({"action": "read"})),
);
assert_eq!(read, Some(Duration::from_secs(DEFAULT_TOOL_TIMEOUT_SECS)));
}
#[test]
fn watchdog_from_secs_zero_disables() {
assert!(watchdog_from_secs(0).is_none());
}
#[test]
fn watchdog_from_secs_positive_maps_to_duration() {
assert_eq!(watchdog_from_secs(5).unwrap().as_secs(), 5);
assert_eq!(
watchdog_from_secs(DEFAULT_TOOL_TIMEOUT_SECS)
.unwrap()
.as_secs(),
120
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn watchdog_returns_error_on_hung_handler() {
use std::sync::atomic::{AtomicBool, Ordering};
let stop = std::sync::Arc::new(AtomicBool::new(false));
let stop_in = stop.clone();
let join = tokio::task::spawn_blocking(move || {
for _ in 0..400 {
if stop_in.load(Ordering::Relaxed) {
break;
}
std::thread::sleep(Duration::from_millis(50));
}
Ok(ToolOutput::simple("late".to_string()))
});
let start = std::time::Instant::now();
let result =
LeanCtxServer::watchdog_join("mock", join, Some(Duration::from_millis(200))).await;
let elapsed = start.elapsed();
stop.store(true, Ordering::Relaxed);
assert!(result.is_err(), "hung handler must surface as an error");
assert!(
elapsed < Duration::from_secs(2),
"watchdog must fire promptly, took {elapsed:?}"
);
}
#[cfg(not(feature = "no-jail"))]
async fn server_rooted_in(root: &std::path::Path) -> LeanCtxServer {
let server = LeanCtxServer::new_with_startup(
None,
None,
crate::tools::SessionMode::Personal,
"default",
"default",
);
let root = root.to_string_lossy().to_string();
let mut session = server.session.write().await;
session.project_root = Some(root.clone());
session.shell_cwd = Some(root);
drop(session);
server
}
#[cfg(not(feature = "no-jail"))]
fn git_project(dir: &std::path::Path) -> std::path::PathBuf {
std::fs::create_dir_all(dir.join(".git")).unwrap();
std::fs::write(dir.join("a.txt"), "before\n").unwrap();
dir.canonicalize().unwrap()
}
#[cfg(not(feature = "no-jail"))]
async fn edit(server: &LeanCtxServer, file: &str) -> String {
let edit = serde_json::json!({
"path": file, "old_string": "before", "new_string": "after"
});
server
.dispatch_tool("ctx_edit", edit.as_object(), false)
.await
.map_or_else(|e| e.message.to_string(), |(text, ..)| text)
}
#[cfg(not(feature = "no-jail"))]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[allow(clippy::await_holding_lock)]
async fn a_session_in_home_adopts_its_first_project_writable_and_once() {
let _iso = lean_ctx::core::data_dir::isolated_data_dir();
let tmp = lean_ctx::core::pathjail_autobind::adoption_fixture_tempdir();
let home = tmp.path().join("home");
std::fs::create_dir_all(&home).unwrap();
let home = home.canonicalize().unwrap();
let _home = lean_ctx::test_env::VarGuard::set("HOME", &home);
let repo = git_project(&home.join("code/app"));
let other = git_project(&home.join("code/other"));
let server = server_rooted_in(&home).await;
let file = repo.join("a.txt").to_string_lossy().to_string();
let read = serde_json::json!({ "path": file, "mode": "full" });
let (text, ..) = server
.dispatch_tool("ctx_read", read.as_object(), false)
.await
.unwrap();
assert!(text.contains("before"), "{text}");
let root = repo.to_string_lossy().to_string();
assert_eq!(
server.session.read().await.project_root.as_deref(),
Some(root.as_str())
);
let text = edit(&server, &file).await;
assert_eq!(std::fs::read_to_string(&file).unwrap(), "after\n", "{text}");
let other_file = other.join("a.txt").to_string_lossy().to_string();
let read = serde_json::json!({ "path": other_file, "mode": "full" });
let _ = server
.dispatch_tool("ctx_read", read.as_object(), false)
.await;
assert_eq!(
server.session.read().await.project_root.as_deref(),
Some(root.as_str()),
"only the first adoption binds"
);
}
#[cfg(not(feature = "no-jail"))]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[allow(clippy::await_holding_lock)]
async fn a_first_write_from_an_agent_dir_adopts_the_project_and_writes() {
let _iso = lean_ctx::core::data_dir::isolated_data_dir();
let tmp = lean_ctx::core::pathjail_autobind::adoption_fixture_tempdir();
let home = tmp.path().join("home");
let agent = home.join(".copilot");
std::fs::create_dir_all(&agent).unwrap();
let home = home.canonicalize().unwrap();
let _home = lean_ctx::test_env::VarGuard::set("HOME", &home);
let repo = git_project(&home.join("code/app"));
let server = server_rooted_in(&agent.canonicalize().unwrap()).await;
let file = repo.join("a.txt").to_string_lossy().to_string();
let text = edit(&server, &file).await;
assert_eq!(std::fs::read_to_string(&file).unwrap(), "after\n", "{text}");
assert_eq!(
server.session.read().await.project_root.as_deref(),
Some(repo.to_string_lossy().as_ref())
);
let adoptions: Vec<_> = lean_ctx::core::audit_trail::load_recent(1_000)
.into_iter()
.filter(|e| {
e.action
.as_deref()
.is_some_and(|a| a.starts_with("jail_autobind:adopted"))
})
.collect();
assert_eq!(adoptions.len(), 1, "{adoptions:?}");
assert_eq!(adoptions[0].tool, "ctx_edit");
let action = adoptions[0].action.as_deref().unwrap();
assert!(
action.ends_with(&format!("|root={}", repo.to_string_lossy())),
"{action}"
);
}
#[cfg(not(feature = "no-jail"))]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[allow(clippy::await_holding_lock)]
async fn an_adopted_project_keeps_its_hooks_closed_to_writes() {
let _iso = lean_ctx::core::data_dir::isolated_data_dir();
let tmp = lean_ctx::core::pathjail_autobind::adoption_fixture_tempdir();
let home = tmp.path().join("home");
std::fs::create_dir_all(&home).unwrap();
let home = home.canonicalize().unwrap();
let _home = lean_ctx::test_env::VarGuard::set("HOME", &home);
let repo = git_project(&home.join("code/b"));
let server = server_rooted_in(&home).await;
let readme = repo.join("a.txt").to_string_lossy().to_string();
let read = serde_json::json!({ "path": readme, "mode": "full" });
server
.dispatch_tool("ctx_read", read.as_object(), false)
.await
.unwrap();
assert_eq!(
server.session.read().await.project_root.as_deref(),
Some(repo.to_string_lossy().as_ref())
);
for hook in [".git/hooks/pre-commit", ".husky/pre-commit", ".envrc"] {
let file = repo.join(hook);
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
std::fs::write(&file, "before\n").unwrap();
let text = edit(&server, &file.to_string_lossy()).await;
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
"before\n",
"{hook}: {text}"
);
assert!(text.contains("lean-ctx allow-path"), "{hook}: {text}");
}
let text = edit(&server, &readme).await;
assert_eq!(
std::fs::read_to_string(&readme).unwrap(),
"after\n",
"{text}"
);
}
#[cfg(not(feature = "no-jail"))]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[allow(clippy::await_holding_lock)]
async fn a_refused_first_write_leaves_the_session_on_home() {
let _iso = lean_ctx::core::data_dir::isolated_data_dir();
let tmp = lean_ctx::core::pathjail_autobind::adoption_fixture_tempdir();
let home = tmp.path().join("home");
std::fs::create_dir_all(&home).unwrap();
let home = home.canonicalize().unwrap();
let _home = lean_ctx::test_env::VarGuard::set("HOME", &home);
let repo = git_project(&home.join("code/b"));
let documents = home.join("Documents");
std::fs::create_dir_all(&documents).unwrap();
std::fs::write(documents.join("package.json"), "{}").unwrap();
let server = server_rooted_in(&home).await;
let home_root = home.to_string_lossy().to_string();
let hook = repo.join(".git/hooks/pre-commit");
let notes = documents.join("notes.md");
for file in [&hook, ¬es] {
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
std::fs::write(file, "before\n").unwrap();
let text = edit(&server, &file.to_string_lossy()).await;
assert_eq!(std::fs::read_to_string(file).unwrap(), "before\n", "{text}");
assert_eq!(
server.session.read().await.project_root.as_deref(),
Some(home_root.as_str()),
"{}: {text}",
file.display()
);
}
let readme = repo.join("a.txt").to_string_lossy().to_string();
let text = edit(&server, &readme).await;
assert_eq!(
std::fs::read_to_string(&readme).unwrap(),
"after\n",
"{text}"
);
assert_eq!(
server.session.read().await.project_root.as_deref(),
Some(repo.to_string_lossy().as_ref())
);
}
#[cfg(not(feature = "no-jail"))]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[allow(clippy::await_holding_lock)]
async fn racing_first_calls_adopt_one_project_and_refuse_the_other() {
let _iso = lean_ctx::core::data_dir::isolated_data_dir();
let tmp = lean_ctx::core::pathjail_autobind::adoption_fixture_tempdir();
let home = tmp.path().join("home");
std::fs::create_dir_all(&home).unwrap();
let home = home.canonicalize().unwrap();
let _home = lean_ctx::test_env::VarGuard::set("HOME", &home);
let projects = ["alpha", "beta"].map(|name| git_project(&home.join("code").join(name)));
let server = server_rooted_in(&home).await;
let barrier = std::sync::Arc::new(tokio::sync::Barrier::new(2));
let calls = projects.clone().map(|repo| {
let server = server.clone();
let barrier = std::cell::RefCell::new(Some(barrier.clone()));
tokio::spawn(crate::tools::ADOPTION_BARRIER.scope(barrier, async move {
let file = repo.join("a.txt").to_string_lossy().to_string();
edit(&server, &file).await
}))
});
let mut outputs = Vec::new();
for call in calls {
let output = tokio::time::timeout(Duration::from_secs(60), call)
.await
.expect("both racing calls reach the adoption barrier");
outputs.push(output.unwrap());
}
let bound = server.session.read().await.project_root.clone().unwrap();
let winner = projects
.iter()
.position(|repo| repo.to_string_lossy() == bound)
.expect("one of the two projects is adopted");
for (i, repo) in projects.iter().enumerate() {
let written = std::fs::read_to_string(repo.join("a.txt")).unwrap() == "after\n";
assert_eq!(written, i == winner, "{}: {}", repo.display(), outputs[i]);
}
}
#[cfg(not(feature = "no-jail"))]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[allow(clippy::await_holding_lock)]
async fn a_session_reset_to_home_after_adopting_never_adopts_again() {
let _iso = lean_ctx::core::data_dir::isolated_data_dir();
let tmp = lean_ctx::core::pathjail_autobind::adoption_fixture_tempdir();
let home = tmp.path().join("home");
std::fs::create_dir_all(&home).unwrap();
let home = home.canonicalize().unwrap();
let _home = lean_ctx::test_env::VarGuard::set("HOME", &home);
let first = git_project(&home.join("code/first"));
let second = git_project(&home.join("code/second"));
let server = server_rooted_in(&home).await;
let path = |repo: &std::path::Path| repo.join("a.txt").to_string_lossy().to_string();
server.resolve_path(&path(&first)).await.unwrap();
let bound = server.session.read().await.project_root.clone();
assert_eq!(bound.as_deref(), Some(first.to_string_lossy().as_ref()));
let home_root = home.to_string_lossy().to_string();
server.session.write().await.project_root = Some(home_root.clone());
let _ = server.resolve_path(&path(&second)).await;
let bound = server.session.read().await.project_root.clone();
assert_eq!(
bound.as_deref(),
Some(home_root.as_str()),
"a reset session keeps its root; the adoption happened once"
);
}
#[cfg(not(feature = "no-jail"))]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[allow(clippy::await_holding_lock)]
async fn shared_workspace_and_pinned_sessions_never_adopt() {
let _iso = lean_ctx::core::data_dir::isolated_data_dir();
let tmp = lean_ctx::core::pathjail_autobind::adoption_fixture_tempdir();
let home = tmp.path().join("home");
std::fs::create_dir_all(&home).unwrap();
let home = home.canonicalize().unwrap();
let home_root = home.to_string_lossy().to_string();
let _home = lean_ctx::test_env::VarGuard::set("HOME", &home);
let repo = git_project(&home.join("code/app"));
let file = repo.join("a.txt").to_string_lossy().to_string();
let mut shared = server_rooted_in(&home).await;
shared.session_mode = crate::tools::SessionMode::Shared;
let mut cases = vec![("shared", shared, Some(home_root.clone()))];
{
let _workspace = lean_ctx::test_env::VarGuard::set(
lean_ctx::core::workspace_authority::ENV_FILE,
tmp.path().join("workspace.json"),
);
let server = server_rooted_in(&home).await;
let _ = server.resolve_path(&file).await;
cases.push(("workspace", server, Some(home_root.clone())));
}
{
let pinned = home.join("pinned");
std::fs::create_dir_all(&pinned).unwrap();
let _pinned = lean_ctx::test_env::VarGuard::set("LEAN_CTX_PROJECT_ROOT", &pinned);
let server = server_rooted_in(&pinned).await;
server.session.write().await.project_root = None;
let _ = server.resolve_path(&file).await;
cases.push(("pinned", server, None));
}
let _ = cases[0].1.resolve_path(&file).await;
for (mode, server, root) in cases {
assert_eq!(
server.session.read().await.project_root.as_deref(),
root.as_deref(),
"{mode}: the session root stays"
);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn watchdog_passes_through_fast_handler() {
let join = tokio::task::spawn_blocking(|| Ok(ToolOutput::simple("ok".to_string())));
let result = LeanCtxServer::watchdog_join("mock", join, Some(Duration::from_secs(5))).await;
assert_eq!(result.unwrap().text, "ok");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn watchdog_none_awaits_handler_to_completion() {
let join = tokio::task::spawn_blocking(|| Ok(ToolOutput::simple("ok".to_string())));
let result = LeanCtxServer::watchdog_join("ctx_shell", join, None).await;
assert_eq!(result.unwrap().text, "ok");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn handler_panic_becomes_error_not_crash() {
let join: tokio::task::JoinHandle<Result<ToolOutput, ErrorData>> =
tokio::task::spawn_blocking(|| panic!("simulated handler panic"));
let result = LeanCtxServer::watchdog_join("mock", join, Some(Duration::from_secs(5))).await;
assert!(
result.is_err(),
"a handler panic must surface as an error; the server process survives"
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_shared_server_refuses_cloud_tasks() {
if lean_ctx::test_env::run_in_own_process(
"server::dispatch::tests::a_shared_server_refuses_cloud_tasks",
&[(lean_ctx_cloud::PREVIEW_ENV, "1")],
) {
return;
}
let mut server = crate::tools::create_server();
server.session_mode = crate::tools::SessionMode::Shared;
let mut args = serde_json::Map::new();
args.insert("action".into(), Value::String("list".into()));
let (text, ..) = server
.dispatch_tool("ctx_tasks", Some(&args), false)
.await
.unwrap();
assert!(text.contains("only in a personal MCP session"), "{text}");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn cloud_tools_are_withheld_while_the_switch_is_off() {
if lean_ctx_cloud::available_locally() {
return;
}
let store = tempfile::tempdir().unwrap();
let store = store.path().to_str().unwrap();
if lean_ctx::test_env::run_in_own_process(
"server::dispatch::tests::cloud_tools_are_withheld_while_the_switch_is_off",
&[
("LEAN_CTX_DATA_DIR", store),
("LEAN_CTX_CONFIG_DIR", store),
("LEAN_CTX_STATE_DIR", store),
("LEAN_CTX_CACHE_DIR", store),
],
) {
return;
}
use crate::server::dynamic_tools::CLOUD_TOOLS;
use lean_ctx::core::tool_profiles::ToolProfile;
let registry = crate::server::registry::build_registry();
let mut surfaces = vec![registry.tool_defs(), registry.active_tool_defs()];
for profile in [
ToolProfile::Minimal,
ToolProfile::Standard,
ToolProfile::Power,
] {
surfaces.push(registry.profile_tool_defs(&profile));
}
for defs in &surfaces {
for def in defs {
assert!(!CLOUD_TOOLS.contains(&def.name.as_ref()), "{}", def.name);
}
}
for name in CLOUD_TOOLS {
assert!(
!crate::server::tool_visibility::is_tool_visible(
name,
&ToolProfile::Power,
&[],
crate::server::tool_visibility::ClientQuirks::default(),
true,
),
"{name}"
);
let found = lean_ctx::tool_defs::discover_tools(name);
assert!(
!found
.lines()
.any(|l| l.trim_start().starts_with(&format!("{name} —"))),
"{found}"
);
}
let server = crate::tools::create_server();
let line = lean_ctx_cloud::TOOL_NOT_AVAILABLE;
for name in CLOUD_TOOLS {
let mut args = serde_json::Map::new();
args.insert("action".into(), Value::String("list".into()));
let (direct, ..) = server
.dispatch_tool(name, Some(&args), false)
.await
.unwrap();
assert_eq!(direct, line);
let mut wrapped = serde_json::Map::new();
wrapped.insert("name".into(), Value::String((*name).into()));
wrapped.insert("arguments".into(), Value::Object(args.clone()));
let (via_call, ..) = server
.dispatch_tool("ctx_call", Some(&wrapped), false)
.await
.unwrap();
assert_eq!(via_call, line);
for (outer, outer_args) in [
(*name, args.clone()),
("ctx_call", wrapped.clone()),
("ctx", {
let mut meta = args.clone();
meta.insert("tool".into(), Value::String((*name).into()));
meta
}),
] {
let request =
rmcp::model::CallToolRequestParams::new(outer).with_arguments(outer_args);
let result = server.call_tool_guarded(request).await.unwrap();
assert_eq!(result.is_error, Some(true), "{outer}");
let text: Vec<_> = result
.content
.iter()
.filter_map(|block| block.as_text())
.map(|block| block.text.as_str())
.collect();
assert_eq!(text, [line], "{outer}");
}
}
}
#[test]
fn cloud_tools_return_with_the_preview() {
if lean_ctx::test_env::run_in_own_process(
"server::dispatch::tests::cloud_tools_return_with_the_preview",
&[(lean_ctx_cloud::PREVIEW_ENV, "1")],
) {
return;
}
let defs = crate::server::registry::build_registry().tool_defs();
for name in crate::server::dynamic_tools::CLOUD_TOOLS {
assert!(defs.iter().any(|def| def.name.as_ref() == *name), "{name}");
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn unknown_tool_suggests_closest_registered_name() {
let server = crate::tools::create_server();
let err = server
.dispatch_tool("ctx_raed", None, false)
.await
.expect_err("typo'd tool must error");
assert!(
err.message.contains("Unknown tool: ctx_raed"),
"unexpected message: {}",
err.message
);
assert!(
err.message.contains("did you mean 'ctx_read'"),
"missing suggestion: {}",
err.message
);
let err = server
.dispatch_tool("ctx_overview", None, false)
.await
.expect_err("removed tool must error");
assert!(
err.message
.starts_with("ctx_overview was removed; use ctx_compose instead"),
"unexpected message: {}",
err.message
);
let err = server
.dispatch_tool("zzz_qqq_www", None, false)
.await
.expect_err("unrelated name must error");
assert!(
!err.message.contains("did you mean"),
"no confident suggestion for garbage: {}",
err.message
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn ctx_call_forwards_flattened_inner_arguments() {
let server = crate::tools::create_server();
fn msg(
r: Result<
(
String,
usize,
Option<ShellOutcome>,
Option<Vec<ContentBlock>>,
),
ErrorData,
>,
) -> String {
match r {
Ok((text, ..)) => text,
Err(e) => e.message.to_string(),
}
}
let mut bare = serde_json::Map::new();
bare.insert("name".into(), Value::String("ctx_read".into()));
let bare = msg(server.dispatch_tool("ctx_call", Some(&bare), false).await);
assert!(
bare.contains("path is required"),
"an argument-less inner call must still say what is missing: {bare}"
);
let mut flat = serde_json::Map::new();
flat.insert("name".into(), Value::String("ctx_read".into()));
flat.insert("path".into(), Value::String("Cargo.toml".into()));
let flat = msg(server.dispatch_tool("ctx_call", Some(&flat), false).await);
assert!(
!flat.contains("path is required"),
"flattened arguments must reach the inner tool: {flat}"
);
let mut nested = serde_json::Map::new();
nested.insert("name".into(), Value::String("ctx_read".into()));
nested.insert(
"arguments".into(),
serde_json::json!({ "path": "Cargo.toml" }),
);
let nested = msg(server.dispatch_tool("ctx_call", Some(&nested), false).await);
assert!(
!nested.contains("path is required"),
"nested arguments must keep working: {nested}"
);
let mut typo = serde_json::Map::new();
typo.insert("name".into(), Value::String("ctx_read".into()));
typo.insert("args".into(), serde_json::json!({ "path": "Cargo.toml" }));
let typo = msg(server.dispatch_tool("ctx_call", Some(&typo), false).await);
assert!(
typo.contains("unknown key 'args'"),
"the #658 misspelling hint must survive: {typo}"
);
}
}
#[cfg(test)]
mod workflow_gate_tests {
use lean_ctx::core::context_admission::stored::lineage_support::{governed, project, scoped};
use lean_ctx::core::policy::runtime::TestPolicyOverride;
use lean_ctx::core::workflow::gate::test_support::{review, workflow_file};
use lean_ctx::core::workflow::{is_withheld_sentinel, load_active, save_active};
use serde_json::{Map, Value, json};
fn call(inner: &str, arguments: &Value) -> Map<String, Value> {
let mut args = Map::new();
args.insert("name".into(), Value::String(inner.into()));
args.insert("arguments".into(), arguments.clone());
args
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_ctx_call_gate_keeps_a_withheld_workflow_closed() {
let _data = governed();
let _community = TestPolicyOverride::set(None);
let (_directory, root) = project();
let (_other_directory, other) = project();
scoped(&root, || save_active(&review())).expect("saved in its project");
let stored = std::fs::read(workflow_file()).expect("stored workflow");
let server = crate::tools::LeanCtxServer::new_with_project_root(Some(&other));
let mut closed = scoped(&other, load_active)
.expect("load")
.expect("a withheld workflow is still a workflow");
assert!(is_withheld_sentinel(&closed));
closed.updated_at =
lean_ctx_time::UtcDateTime::now() - lean_ctx_time::Duration::minutes(45);
*server.workflow.write().await = Some(closed);
for (inner, arguments) in [
("ctx_read", json!({ "path": "Cargo.toml" })),
(
"ctx_session",
json!({ "action": "finding", "value": "noted" }),
),
(
"ctx_session",
json!({ "action": "decision", "value": "decided" }),
),
] {
let (reply, ..) = server
.dispatch_tool("ctx_call", Some(&call(inner, &arguments)), false)
.await
.expect("a refusal is a reply");
assert!(
reply.contains("withheld by the context gateway"),
"{inner}: {reply}"
);
assert!(!reply.contains("review"), "{reply}");
}
assert!(
server
.workflow
.read()
.await
.as_ref()
.is_some_and(is_withheld_sentinel),
"not cleared by its age"
);
assert_eq!(
std::fs::read(workflow_file()).expect("kept"),
stored,
"the withheld workflow is byte-identical on disk"
);
let real = scoped(&root, load_active).expect("load").expect("active");
assert!(!is_withheld_sentinel(&real));
*server.workflow.write().await = Some(real);
let (reply, ..) = server
.dispatch_tool(
"ctx_call",
Some(&call("ctx_shell", &json!({ "command": "true" }))),
false,
)
.await
.expect("a refusal is a reply");
assert!(reply.contains("blocked by workflow 'review'"), "{reply}");
}
}