1use super::super::{
4 CallToolRequestParams, CallToolResult, ErrorData, LeanCtxServer, elicitation, helpers,
5 permission_inheritance,
6};
7use lean_ctx::core::ocla::response_cache::{
8 CachedResponse, ResponseCache, ResponseCacheKey, global_response_cache,
9};
10use rmcp::model::{ContentBlock, MetaObject};
11use serde::Deserialize;
12use serde_json::{Map, Value};
13use std::{
14 sync::Arc,
15 time::{Duration, Instant},
16};
17
18mod kernel;
19pub(super) mod replay_lineage;
20
21#[cfg(test)]
22mod task_lineage_tests;
23
24const CACHEABLE_TOOLS: [&str; 3] = ["ctx_search", "ctx_tree", "ctx_glob"];
25
26struct McpEntitlements {
27 config: std::sync::Arc<lean_ctx::core::config::Config>,
28}
29
30struct PreparedMcpCall {
31 name: String,
32 args: Option<Map<String, Value>>,
33 minimal: bool,
34 config: std::sync::Arc<lean_ctx::core::config::Config>,
35 machine_readable: bool,
36 auto_context: Option<String>,
37 throttle_warning: Option<String>,
38 args_fp: String,
39 decision_context: Option<lean_ctx::core::execution_lifecycle::TaskContext>,
40 kernel_handoff: lean_ctx::core::context_kernel::bridge::runtime::KernelPlanningHandoff,
41 cache_key: Option<ResponseCacheKey>,
42}
43
44enum PreparedCallResult {
45 Terminal(CallToolResult, &'static str),
46 Cached(CallToolResult),
47 Ready(Box<PreparedMcpCall>),
48}
49
50impl PreparedCallResult {
51 fn into_replay_override(self) -> Option<CallToolResult> {
52 match self {
53 Self::Terminal(result, _) => Some(result),
54 Self::Cached(_) | Self::Ready(_) => None,
55 }
56 }
57}
58
59enum McpDispatched {
60 Terminal(CallToolResult, &'static str),
61 Raw {
62 call: Box<PreparedMcpCall>,
63 primitive: super::pipeline::McpPrimitive,
64 },
65}
66
67fn host_hook_refusal(mut result: CallToolResult) -> CallToolResult {
72 result.is_error = Some(true);
73 result
74}
75
76fn loop_throttle_refusal(
80 throttle: &lean_ctx::core::loop_detection::ThrottleResult,
81) -> Option<CallToolResult> {
82 (throttle.level == lean_ctx::core::loop_detection::ThrottleLevel::Blocked).then(|| {
83 CallToolResult::error(vec![ContentBlock::text(
84 throttle.message.clone().unwrap_or_default(),
85 )])
86 })
87}
88
89struct McpProcessedCall {
90 result: CallToolResult,
91 pipeline: Option<super::pipeline::McpProcessed>,
92 cache_key: Option<ResponseCacheKey>,
93 skip_reason: Option<&'static str>,
94}
95
96struct McpDriver<'a> {
97 server: &'a LeanCtxServer,
98 request: Option<CallToolRequestParams>,
99 entitlements: Option<McpEntitlements>,
100 prepared: Option<PreparedCallResult>,
101 checkpoint: Option<super::pipeline::McpCheckpointIntent>,
102 pending_cache_key: Option<ResponseCacheKey>,
103 native_receipt_capture: Option<Arc<crate::server::native_receipts::NativeReceiptCapture>>,
104 native_receipt_metadata: Option<Value>,
105 input_tokens: u64,
106}
107
108#[derive(Deserialize)]
109#[serde(rename_all = "camelCase")]
110struct CachedCallToolResult {
111 content: Vec<ContentBlock>,
112 #[serde(default)]
113 structured_content: Option<Value>,
114 #[serde(default)]
115 is_error: Option<bool>,
116 #[serde(default, rename = "_meta")]
117 meta: Option<MetaObject>,
118}
119
120pub(super) fn response_cache_key(
121 tool_name: &str,
122 arguments: Option<&Map<String, Value>>,
123 project_root: &str,
124) -> Option<ResponseCacheKey> {
125 if crate::server::native_receipts::requested(tool_name, arguments) {
126 return None;
128 }
129 if lean_ctx::core::workspace_authority::is_configured() {
132 return None;
133 }
134 if tool_name == "ctx_search"
137 && arguments.is_some_and(crate::tools::registered::ctx_search::uses_kernel_context)
138 {
139 return None;
140 }
141 let policy = lean_ctx::core::policy::runtime::active();
142 if policy
143 .as_ref()
144 .is_some_and(|policy| !policy.tool_allowed(tool_name))
145 {
146 return None;
147 }
148 if !CACHEABLE_TOOLS.contains(&tool_name) {
149 return None;
150 }
151 let revision = corpus_revision(arguments, project_root)?;
158 Some({
159 let mut input = Vec::with_capacity(project_root.len() + 1);
160 input.extend_from_slice(project_root.as_bytes());
161 input.push(0);
162 input.extend_from_slice(&revision.to_be_bytes());
163 input.push(0);
164 input.extend_from_slice(
165 &serde_json::to_vec(&arguments).expect("JSON arguments must serialize"),
166 );
167 if let Some(policy) = policy {
168 input.push(0);
169 input.extend_from_slice(
170 &serde_json::to_vec(&policy.resolved).expect("resolved policy is serializable"),
171 );
172 }
173 let digest = blake3::hash(&input);
174 let mut hash_bytes = [0; 8];
175 hash_bytes.copy_from_slice(&digest.as_bytes()[..8]);
176 let arguments_hash = u64::from_be_bytes(hash_bytes);
177 ResponseCacheKey::new(tool_name, arguments_hash, 0.0, 0)
178 })
179}
180
181fn corpus_revision(arguments: Option<&Map<String, Value>>, project_root: &str) -> Option<u64> {
184 let arg = arguments
185 .and_then(|args| args.get("path"))
186 .and_then(Value::as_str)
187 .filter(|path| !path.trim().is_empty());
188 let root = match arg {
189 Some(path) if std::path::Path::new(path).is_absolute() => std::path::PathBuf::from(path),
190 Some(path) if !project_root.is_empty() => std::path::Path::new(project_root).join(path),
191 None if !project_root.is_empty() => std::path::PathBuf::from(project_root),
192 Some(_) | None => return None,
193 };
194 if !root.exists() {
195 return Some(0);
197 }
198 lean_ctx::core::search_index::corpus_signature(&root.to_string_lossy(), true, false)
199}
200
201fn cache_allowed_for_current_egress(config: &lean_ctx::core::config::Config) -> bool {
202 !lean_ctx::core::context_admission::stored::source_authority_required()
207 && !lean_ctx::core::policy::runtime::is_active()
208 && !config.sensitivity_effective().enabled_effective()
209 && lean_ctx::core::redaction::redaction_enabled_for_active_role()
210}
211
212fn bound_cache_allowed(config: &lean_ctx::core::config::Config) -> bool {
221 lean_ctx::core::context_admission::stored::source_authority_required()
222 && !config.sensitivity_effective().enabled_effective()
223 && lean_ctx::core::redaction::redaction_enabled_for_active_role()
224}
225
226fn project_only_output() -> bool {
229 lean_ctx::core::context_admission::capture::current()
230 .is_some_and(|capture| capture.output_origins().is_empty())
231}
232
233fn cache_lineage_id(key: &ResponseCacheKey) -> String {
235 format!("{}:{:016x}", key.model, key.hash)
236}
237
238pub(super) fn cached_call_result(
239 cache: &ResponseCache,
240 key: &ResponseCacheKey,
241) -> Option<CallToolResult> {
242 let response = cache.get(key);
243 lean_ctx::core::telemetry::global_metrics().record_cache(response.is_some());
244 response.and_then(|cached| {
245 serde_json::from_slice::<CachedCallToolResult>(&cached.body)
246 .ok()
247 .map(|cached| {
248 let mut result = CallToolResult::success(cached.content);
249 result.structured_content = cached.structured_content;
250 result.is_error = cached.is_error;
251 result.meta = cached.meta;
252 result
253 })
254 })
255}
256
257pub(super) fn cache_call_result(
258 cache: &ResponseCache,
259 key: ResponseCacheKey,
260 result: &CallToolResult,
261) {
262 if result.is_error == Some(true) {
263 return;
264 }
265 let Ok(body) = serde_json::to_vec(result) else {
266 return;
267 };
268 let tokens = lean_ctx::core::tokens::count_tokens(&String::from_utf8_lossy(&body))
269 .try_into()
270 .unwrap_or(u64::MAX);
271 cache.put(
272 key,
273 CachedResponse {
274 body,
275 status: 200,
276 tokens,
277 created_at: Instant::now(),
278 ttl: Duration::ZERO,
279 },
280 );
281}
282
283impl LeanCtxServer {
284 pub async fn call_tool_guarded(
288 &self,
289 request: CallToolRequestParams,
290 ) -> Result<CallToolResult, ErrorData> {
291 let authority = lean_ctx::core::workspace_authority::current();
294 let rights = lean_ctx::core::session_rights::current();
297 lean_ctx::core::session_rights::scope(
298 rights,
299 lean_ctx::core::workspace_authority::scope(
300 authority,
301 self.session
302 .scope(Box::pin(self.call_tool_guarded_bound(request))),
303 ),
304 )
305 .await
306 }
307
308 async fn call_tool_guarded_bound(
309 &self,
310 request: CallToolRequestParams,
311 ) -> Result<CallToolResult, ErrorData> {
312 let project = self
313 .session
314 .read()
315 .await
316 .project_root
317 .as_ref()
318 .map(std::path::PathBuf::from);
319 let tick = self
330 .background_tick
331 .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
332 + 1;
333 if tick == 1 || tick.is_multiple_of(10) {
334 let record_version = tick == 1 || tick.is_multiple_of(100);
337 std::thread::spawn(move || {
338 if record_version
339 && lean_ctx::core::telemetry_send::telemetry_send_eligible()
340 && let Err(error) =
341 lean_ctx::core::telemetry_aggregate::record_current_version()
342 {
343 tracing::debug!("telemetry version aggregate unavailable: {error}");
344 }
345 lean_ctx::core::telemetry_send::send_telemetry(
346 lean_ctx::core::telemetry_aggregate::SendTrigger::Periodic,
347 );
348 });
349 }
350 lean_ctx::core::policy::runtime::REQUEST_PROJECT
351 .scope(std::cell::RefCell::new(project), async {
352 self.resolve_roots_once().await;
355 self.session.pin();
356 let (project, session_id) = {
357 let session = self.session.read().await;
358 lean_ctx::core::session::taint::bind(&session.id, &session.taint);
362 (session.project_root.clone(), session.id.clone())
363 };
364 lean_ctx::core::policy::runtime::bind_request_project(project.as_deref());
365 let admissions =
369 lean_ctx::core::context_admission::capture::AdmissionCapture::for_call(
370 lean_ctx::core::context_admission::capture::CallSnapshot::take(),
371 );
372 let tool_name = request.name.to_string();
373 let activity = crate::server::activity::PendingCall::new(
374 &tool_name,
375 request.arguments.as_ref(),
376 );
377 let result = lean_ctx::core::context_admission::capture::ADMISSIONS
378 .scope(
379 Some(admissions.clone()),
380 self.call_tool_guarded_scoped(request),
381 )
382 .await;
383 let result = result.map_err(|error| {
387 if lean_ctx::core::policy::runtime::is_active() {
388 ErrorData::internal_error(
389 "Tool request failed under the current policy",
390 None,
391 )
392 } else {
393 error
394 }
395 });
396 if let Some(taint) = lean_ctx::core::session::taint::snapshot_for(&session_id)
399 .filter(lean_ctx::core::context_admission::origin::InputTaint::is_tainted)
400 {
401 let mut session = self.session.write().await;
402 if session.id == session_id {
403 session.taint.merge(&taint);
404 }
405 }
406 {
407 let failed = result
408 .as_ref()
409 .map_or(true, |r| r.is_error.unwrap_or(false));
410 let (session_id, project_root) = {
411 let session = self.session.read().await;
412 (session.id.clone(), session.project_root.clone())
413 };
414 let client_name = self.client_name.read().await.clone();
415 activity.finish(&session_id, project_root.as_deref(), &client_name, failed);
416 }
417 self.finish_gateway_receipt(admissions, result, &tool_name)
419 .await
420 })
421 .await
422 }
423
424 async fn call_tool_guarded_scoped(
425 &self,
426 request: CallToolRequestParams,
427 ) -> Result<CallToolResult, ErrorData> {
428 if let Some(line) = crate::server::dynamic_tools::withheld_cloud_tool_refusal(
431 &request.name,
432 request.arguments.as_ref(),
433 ) {
434 return Ok(CallToolResult::error(vec![ContentBlock::text(line)]));
435 }
436 if crate::server::native_receipts::requested(&request.name, request.arguments.as_ref())
437 && let Some(authority) = &self.native_receipt_authority
438 {
439 authority
441 .validate_current()
442 .map_err(|code| ErrorData::internal_error(code, None))?;
443 }
444 let config = lean_ctx::core::config::Config::load_arc();
445 let tool_name = request.name.as_ref().to_string();
446 let semantic_call =
450 crate::tools::registered::ctx_call::resolve(&tool_name, request.arguments.as_ref())
451 .ok();
452 let query = semantic_call
453 .as_ref()
454 .and_then(|(_, args)| args.as_ref())
455 .and_then(|args| {
456 args.get("query")
457 .and_then(Value::as_str)
458 .or_else(|| args.get("task").and_then(Value::as_str))
459 })
460 .map(str::to_owned);
461 let input_tokens = request
462 .arguments
463 .as_ref()
464 .and_then(|arguments| serde_json::to_vec(arguments).ok())
465 .map_or(0, |bytes| {
466 u64::try_from(bytes.len() / 4).unwrap_or(u64::MAX)
467 });
468 let raw_idempotency_key = request.meta.as_ref().and_then(|meta| {
469 meta.0
470 .get("requestId")
471 .or_else(|| meta.0.get("idempotencyKey"))
472 .and_then(Value::as_str)
473 .map(str::to_owned)
474 });
475 let (session_id, project_root, stated_task) = {
476 let session = self.session.read().await;
477 let stated_task = session
478 .task
479 .as_ref()
480 .filter(|task| {
481 crate::tools::registered::ctx_read::task_intent_steers_read(
482 task.intent.as_deref(),
483 )
484 })
485 .map(|task| task.description.clone());
486 (
487 session.id.clone(),
488 session.project_root.clone(),
489 stated_task,
490 )
491 };
492 let query = query.or(stated_task);
493 let task_identity = self
494 .native_receipt_authority
495 .as_ref()
496 .map(|authority| authority.admit_task_identity(project_root.as_deref()))
497 .transpose()
498 .map_err(|code| ErrorData::internal_error(code, None))?
499 .flatten();
500 let agent_id = match self.agent_id.read().await.clone() {
501 Some(agent_id) => agent_id,
502 None => self
503 .presence_agent_id
504 .read()
505 .await
506 .clone()
507 .unwrap_or_else(|| "mcp-agent".to_owned()),
508 };
509 let payload_fingerprint = request.arguments.as_ref().map_or_else(String::new, |args| {
510 lean_ctx::core::loop_detection::LoopDetector::fingerprint(&Value::Object(args.clone()))
511 });
512 let idempotency_key = raw_idempotency_key.map(|key| {
513 format!("mcp:{session_id}:{agent_id}:{tool_name}:{payload_fingerprint}:{key}")
514 });
515 let client_name = self.client_name.read().await.clone();
516 let release_name = semantic_call
517 .as_ref()
518 .map_or(tool_name.as_str(), |(name, _)| name)
519 .to_owned();
520 let decision_loop_enabled = config.decision_loop.enabled;
521 let lifecycle = lean_ctx::core::execution_lifecycle::ExecutionLifecycle::global();
522 let replay_key = idempotency_key.clone();
525 let run = lifecycle.run_with_task_identity(
526 lean_ctx::core::execution_lifecycle::ToolRequest {
527 tool_name: semantic_call.map_or(tool_name, |(name, _)| name),
528 query,
529 session_id,
530 agent_id,
531 surface: lean_ctx::core::execution_lifecycle::ToolSurface::Mcp,
532 idempotency_key,
533 },
534 lean_ctx::core::execution_lifecycle::RuntimeContext {
535 client_name: Some(client_name),
536 project_root,
537 },
538 lean_ctx::core::execution_lifecycle::ProductEntitlements {
539 autopilot: decision_loop_enabled,
540 personalized_learning: false,
541 },
542 McpDriver {
543 server: self,
544 request: Some(request),
545 entitlements: Some(McpEntitlements { config }),
546 prepared: None,
547 checkpoint: None,
548 pending_cache_key: None,
549 native_receipt_capture: None,
550 native_receipt_metadata: None,
551 input_tokens,
552 },
553 task_identity,
554 );
555 let outcome = replay_lineage::scope(replay_key, run)
556 .await
557 .map_err(|error| match error {
558 lean_ctx::core::execution_lifecycle::LifecycleRunError::Dispatch(error) => error,
559 lean_ctx::core::execution_lifecycle::LifecycleRunError::ReplayTypeMismatch => {
560 ErrorData::invalid_request("idempotent execution contract mismatch", None)
561 }
562 lean_ctx::core::execution_lifecycle::LifecycleRunError::Aborted(outcome) => {
563 ErrorData::internal_error(
564 format!(
565 "idempotent execution already terminated: {}",
566 outcome.accepted_outcome.outcome_id.as_str()
567 ),
568 None,
569 )
570 }
571 });
572 crate::server::policy_guard::release_outcome(&release_name, outcome)
575 }
576
577 async fn prepare_tool_call(
578 &self,
579 request: CallToolRequestParams,
580 entitlements: McpEntitlements,
581 ) -> Result<PreparedCallResult, ErrorData> {
582 elicitation::increment_call();
583
584 let original_name = request.name.as_ref().to_string();
585 let meta_interaction_mode = request
587 .meta
588 .as_ref()
589 .and_then(|m| m.0.get("interactionMode"))
590 .and_then(|v| v.as_str())
591 .and_then(crate::tools::InteractionMode::from_meta_str);
592 let (resolved_name, resolved_args) = crate::tools::registered::ctx_call::normalize_outer(
593 &original_name,
594 request.arguments.as_ref(),
595 )?;
596 let name = resolved_name.as_str();
597 let args = resolved_args.as_ref();
598 let config = entitlements.config;
599 let audit_agent = self.audit_agent_id().await;
600 if let Some(denied) = Self::guard_role_and_policy(name, &audit_agent) {
601 return Ok(PreparedCallResult::Terminal(
602 denied,
603 "role or policy denied",
604 ));
605 }
606 {
610 let client_name = self.client_name.read().await.clone();
611 let project_root = self.session.read().await.project_root.clone();
612 if let Some(reason) = lean_ctx::core::policy::cloud_agents::agent_refusal(
613 project_root.as_deref().map(std::path::Path::new),
614 &client_name,
615 ) {
616 tracing::warn!(tool = name, %reason, "agent refused by the team policy");
617 return Ok(PreparedCallResult::Terminal(
618 CallToolResult::error(vec![ContentBlock::text(format!(
619 "[POLICY BLOCKED] {reason}. Ask a team admin to allow this agent."
620 ))]),
621 "agent not allowed",
622 ));
623 }
624 if let Some(reason) = lean_ctx::core::policy::cloud_agents::proxy_requirement_refusal(
627 project_root.as_deref().map(std::path::Path::new),
628 &client_name,
629 ) {
630 tracing::warn!(tool = name, %reason, "agent refused by the Cloud policy");
631 return Ok(PreparedCallResult::Terminal(
632 CallToolResult::error(vec![ContentBlock::text(format!(
633 "[POLICY BLOCKED] {reason}. Run `lean-ctx proxy enable` and restart \
634 the agent so its model traffic goes through the LeanCTX proxy."
635 ))]),
636 "agent not routed through the proxy",
637 ));
638 }
639 }
640
641 let inner_call = if name == "ctx_call" {
647 match crate::tools::registered::ctx_call::resolve_inner(args) {
648 Ok(inner) => Some(inner),
649 Err(error) => {
652 return Ok(PreparedCallResult::Terminal(
653 CallToolResult::error(vec![ContentBlock::text(error.message.to_string())]),
654 "invalid params",
655 ));
656 }
657 }
658 } else {
659 None
660 };
661 let (guard_name, guard_args): (&str, Option<&serde_json::Map<_, _>>) = match &inner_call {
662 Some((n, a)) => (n.as_str(), a.as_ref()),
663 None => (name, args),
664 };
665 if inner_call.is_some() {
668 if let Some(denied) = Self::guard_role_and_policy(guard_name, &audit_agent) {
669 return Ok(PreparedCallResult::Terminal(
670 denied,
671 "inner role or policy denied",
672 ));
673 }
674 if let Some(denied) = self.guard_workflow(guard_name).await {
675 return Ok(PreparedCallResult::Terminal(
676 denied,
677 "inner workflow denied",
678 ));
679 }
680 if let Some(denied) = self.guard_session_rights(guard_name) {
681 return Ok(PreparedCallResult::Terminal(
682 denied,
683 "inner session rights denied",
684 ));
685 }
686 }
687
688 if let Some(mode) = meta_interaction_mode {
690 let prev = self
691 .interaction_mode
692 .swap(mode as u8, std::sync::atomic::Ordering::Relaxed);
693 if prev != mode as u8 {
694 tracing::info!(
695 ?mode,
696 "interaction mode changed — sending tools/list_changed"
697 );
698 if let Some(peer) = self.peer.read().await.as_ref() {
699 crate::server::notifications::send_tools_list_changed(peer).await;
700 }
701 }
702 }
703
704 {
706 use crate::tools::InteractionMode;
707 let current = InteractionMode::from_u8(
708 self.interaction_mode
709 .load(std::sync::atomic::Ordering::Relaxed),
710 );
711 if current == InteractionMode::Plan {
712 let plan_tools = lean_ctx::core::editor_registry::plan_mode::plan_mode_tools();
713 if !plan_tools.contains(&guard_name) {
714 let result = CallToolResult::error(vec![ContentBlock::text(format!(
715 "[PLAN MODE] Tool '{guard_name}' is not available in plan/readonly mode. Switch to agent/edit mode to use this tool."
716 ))]);
717 return Ok(PreparedCallResult::Terminal(result, "plan mode denied"));
718 }
719 }
720 }
721
722 let agent = match self.agent_id.read().await.clone() {
726 Some(agent) => Some(agent),
727 None => self.presence_agent_id.read().await.clone(),
728 };
729 if let Some(message) =
730 lean_ctx_cloud::bus::control::tool_refusal(agent.as_deref(), guard_name)
731 {
732 return Ok(PreparedCallResult::Terminal(
733 CallToolResult::error(vec![ContentBlock::text(message)]),
734 "cloud control denied",
735 ));
736 }
737 if let Some(message) = lean_ctx_cloud::bus::veto::take_refusal(agent.as_deref(), guard_name)
740 {
741 return Ok(PreparedCallResult::Terminal(
742 CallToolResult::error(vec![ContentBlock::text(message)]),
743 "cloud veto",
744 ));
745 }
746
747 if let Some(blocked) = Self::guard_egress(guard_name, guard_args, &audit_agent) {
748 return Ok(PreparedCallResult::Terminal(blocked, "egress denied"));
749 }
750
751 if let Some(blocked) = self.guard_workflow(name).await {
752 return Ok(PreparedCallResult::Terminal(blocked, "workflow denied"));
753 }
754
755 if let Some(blocked) = self.guard_session_rights(name) {
756 return Ok(PreparedCallResult::Terminal(
757 blocked,
758 "session rights denied",
759 ));
760 }
761
762 let machine_readable = self
780 .registry
781 .as_ref()
782 .and_then(|registry| registry.get_arc(guard_name))
783 .is_some_and(|tool| tool.produces_machine_readable(guard_args));
784
785 let args_fp = args
790 .map(|a| {
791 lean_ctx::core::loop_detection::LoopDetector::fingerprint(
792 &serde_json::Value::Object(a.clone()),
793 )
794 })
795 .unwrap_or_default();
796 let throttle_result = {
797 let semantic_fp = guard_args
798 .map(|args| {
799 lean_ctx::core::loop_detection::LoopDetector::fingerprint(&Value::Object(
800 args.clone(),
801 ))
802 })
803 .unwrap_or_default();
804 let fp = &semantic_fp;
805 let detector_timeout = tokio::time::timeout(
806 std::time::Duration::from_secs(3),
807 self.loop_detector.write(),
808 )
809 .await;
810 if crate::server::dynamic_tools::INTERNAL_HOST_TOOLS.contains(&guard_name) {
811 lean_ctx::core::loop_detection::ThrottleResult::default()
814 } else if let Ok(mut detector) = detector_timeout {
815 let is_search =
816 lean_ctx::core::loop_detection::LoopDetector::is_search_tool(guard_name);
817 let is_search_shell = guard_name == "ctx_shell" && {
818 let cmd = guard_args
819 .and_then(|a| a.get("command"))
820 .and_then(|v| v.as_str())
821 .unwrap_or("");
822 lean_ctx::core::loop_detection::LoopDetector::is_search_shell_command(cmd)
823 };
824
825 if is_search || is_search_shell {
826 let search_pattern = guard_args.and_then(|a| {
827 a.get("pattern")
828 .or_else(|| a.get("query"))
829 .and_then(|v| v.as_str())
830 });
831 let shell_pattern = if is_search_shell {
832 guard_args
833 .and_then(|a| a.get("command"))
834 .and_then(|v| v.as_str())
835 .and_then(helpers::extract_search_pattern_from_command)
836 } else {
837 None
838 };
839 let pat = search_pattern.or(shell_pattern.as_deref());
840 detector.record_search(guard_name, fp, pat)
841 } else {
842 detector.record_call(guard_name, fp)
843 }
844 } else {
845 tracing::warn!("pre-dispatch: loop_detector write-lock timeout (3s), skipping");
846 lean_ctx::core::loop_detection::ThrottleResult::default()
847 }
848 };
849
850 if let Some(result) = loop_throttle_refusal(&throttle_result) {
851 return Ok(PreparedCallResult::Terminal(
852 result,
853 "loop throttle blocked",
854 ));
855 }
856
857 let throttle_warning =
858 if throttle_result.level == lean_ctx::core::loop_detection::ThrottleLevel::Reduced {
859 throttle_result.message.clone()
860 } else {
861 None
862 };
863
864 if config.permission_inheritance_effective()
871 == lean_ctx::core::config::PermissionInheritance::On
872 {
873 let client_name = self.client_name.read().await.clone();
874 let project_root = self.session.read().await.project_root.clone();
875 let perm = permission_inheritance::check(
876 &client_name,
877 guard_name,
878 guard_args,
879 project_root.as_deref(),
880 &config,
881 );
882 if let Some(blocked) = permission_inheritance::into_call_tool_result(&perm) {
883 tracing::warn!(tool = guard_name, "held back by IDE permission inheritance");
884 return Ok(PreparedCallResult::Terminal(
885 blocked,
886 "permission inheritance denied",
887 ));
888 }
889 }
890
891 let project_root = self
892 .session
893 .read()
894 .await
895 .project_root
896 .clone()
897 .unwrap_or_default();
898 let bound_cache = bound_cache_allowed(&config);
901 let cache_key = (bound_cache || cache_allowed_for_current_egress(&config))
902 .then(|| response_cache_key(name, args, &project_root))
903 .flatten();
904 let call_start = std::time::Instant::now();
905 if let Some(cached) = cache_key
906 .as_ref()
907 .filter(|key| {
909 !bound_cache || replay_lineage::cache_entry_current(&cache_lineage_id(key))
910 })
911 .and_then(|key| cached_call_result(global_response_cache(), key))
912 {
913 self.record_tool_usage(
914 name,
915 call_start,
916 super::pipeline::result_failure(&cached, ""),
917 );
918 return Ok(PreparedCallResult::Cached(cached));
919 }
920
921 Ok(PreparedCallResult::Ready(Box::new(PreparedMcpCall {
922 name: name.to_owned(),
923 args: args.cloned(),
924 minimal: false,
925 config,
926 machine_readable,
927 auto_context: None,
928 throttle_warning,
929 args_fp,
930 decision_context: None,
931 kernel_handoff:
932 lean_ctx::core::context_kernel::bridge::runtime::KernelPlanningHandoff::Suppressed,
933 cache_key,
934 })))
935 }
936
937 fn record_tool_usage(
941 &self,
942 name: &str,
943 started: std::time::Instant,
944 failure: Option<lean_ctx::core::telemetry_failure::Failure>,
945 ) {
946 let Some(tool) = self
947 .registry
948 .as_ref()
949 .and_then(|registry| registry.static_name(name))
950 else {
951 return;
952 };
953 let latency_us = u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX);
954 lean_ctx::core::telemetry::global_metrics()
955 .record_named_tool_failure(tool, latency_us, failure);
956 }
957}
958
959#[async_trait::async_trait]
960impl lean_ctx::core::execution_lifecycle::ExecutionDriver for McpDriver<'_> {
961 type Primitive = McpDispatched;
962 type Processed = McpProcessedCall;
963 type Output = CallToolResult;
964 type Error = ErrorData;
965
966 async fn identify_caller(
967 &mut self,
968 _context: &lean_ctx::core::execution_lifecycle::TaskContext,
969 ) -> Result<lean_ctx::core::execution_lifecycle::StageDisposition, Self::Error> {
970 self.server
971 .ensure_session_presence()
972 .await
973 .map_err(|error| {
974 ErrorData::internal_error(
975 format!("agent bus registration is required before tool execution: {error}"),
976 None,
977 )
978 })?;
979 self.server.check_idle_expiry().await;
980 Ok(lean_ctx::core::execution_lifecycle::StageDisposition::Applied)
981 }
982
983 async fn resolve_workspace(
984 &mut self,
985 _context: &lean_ctx::core::execution_lifecycle::TaskContext,
986 ) -> Result<lean_ctx::core::execution_lifecycle::StageDisposition, Self::Error> {
987 self.server.resolve_roots_once().await;
988 let project = self.server.session.read().await.project_root.clone();
989 lean_ctx::core::policy::runtime::bind_request_project(project.as_deref());
990 Ok(lean_ctx::core::execution_lifecycle::StageDisposition::Applied)
991 }
992
993 async fn resolve_entitlements(
994 &mut self,
995 _context: &lean_ctx::core::execution_lifecycle::TaskContext,
996 ) -> Result<lean_ctx::core::execution_lifecycle::StageDisposition, Self::Error> {
997 if self.entitlements.is_none() {
998 return Err(ErrorData::internal_error(
999 "MCP entitlements were not resolved",
1000 None,
1001 ));
1002 }
1003 Ok(lean_ctx::core::execution_lifecycle::StageDisposition::Applied)
1004 }
1005
1006 async fn apply_security_boundaries(
1007 &mut self,
1008 _context: &lean_ctx::core::execution_lifecycle::TaskContext,
1009 ) -> Result<lean_ctx::core::execution_lifecycle::StageDisposition, Self::Error> {
1010 let request = self.request.take().expect("MCP request consumed once");
1011 let entitlements = self
1012 .entitlements
1013 .take()
1014 .expect("MCP entitlements consumed once");
1015 let host_hook = crate::server::dynamic_tools::targets_internal_host_tool(
1016 request.name.as_ref(),
1017 request.arguments.as_ref(),
1018 );
1019 let prepared = self.server.prepare_tool_call(request, entitlements).await?;
1020 self.prepared = Some(match prepared {
1021 PreparedCallResult::Terminal(result, reason) if host_hook => {
1022 PreparedCallResult::Terminal(host_hook_refusal(result), reason)
1023 }
1024 other => other,
1025 });
1026 Ok(lean_ctx::core::execution_lifecycle::StageDisposition::Applied)
1027 }
1028
1029 async fn validate_cached_replay(
1030 &mut self,
1031 context: &lean_ctx::core::execution_lifecycle::TaskContext,
1032 ) -> Result<Option<Self::Output>, Self::Error> {
1033 self.identify_caller(context).await?;
1034 self.resolve_workspace(context).await?;
1035 self.resolve_entitlements(context).await?;
1036 self.apply_security_boundaries(context).await?;
1037 Ok(self
1044 .prepared
1045 .take()
1046 .expect("MCP replay admission consumed once")
1047 .into_replay_override()
1048 .or_else(replay_lineage::denial))
1049 }
1050
1051 async fn gather_context_strategy(
1052 &mut self,
1053 context: &lean_ctx::core::execution_lifecycle::TaskContext,
1054 ) -> Result<lean_ctx::core::execution_lifecycle::StageDisposition, Self::Error> {
1055 let Some(PreparedCallResult::Ready(call)) = self.prepared.as_mut() else {
1056 return Ok(
1057 lean_ctx::core::execution_lifecycle::StageDisposition::Skipped(
1058 "admission returned a terminal result",
1059 ),
1060 );
1061 };
1062 *self.server.task_envelope.write().await = Some(context.envelope.clone());
1063 call.minimal = call.config.minimal_overhead_effective();
1064 if !call.machine_readable {
1067 let (task, project_root) = {
1068 let session = self.server.session.read().await;
1069 (
1070 session.task.as_ref().map(|task| task.description.clone()),
1071 session.project_root.clone(),
1072 )
1073 };
1074 if !crate::tools::autonomy::delivers_session_briefing(&call.name, call.args.as_ref()) {
1075 crate::tools::autonomy::apply_auto_load_packages_once(
1076 &self.server.autonomy,
1077 project_root.as_deref(),
1078 );
1079 return Ok(lean_ctx::core::execution_lifecycle::StageDisposition::Applied);
1080 }
1081 call.auto_context = lean_ctx::core::session::caller::scope(
1083 Some(self.server.session.instance()),
1084 || {
1085 crate::tools::autonomy::session_wakeup_briefing(
1086 &self.server.autonomy,
1087 &call.name,
1088 task.as_deref(),
1089 project_root.as_deref(),
1090 )
1091 },
1092 );
1093 }
1094 Ok(lean_ctx::core::execution_lifecycle::StageDisposition::Applied)
1095 }
1096
1097 async fn ask_autopilot(
1098 &mut self,
1099 context: &lean_ctx::core::execution_lifecycle::TaskContext,
1100 ) -> Result<lean_ctx::core::execution_lifecycle::StageDisposition, Self::Error> {
1101 if !context.entitlements.autopilot {
1102 if let Some(PreparedCallResult::Ready(call)) = self.prepared.as_mut() {
1103 call.kernel_handoff =
1104 lean_ctx::core::context_kernel::bridge::runtime::KernelPlanningHandoff::Suppressed;
1105 }
1106 return Ok(
1107 lean_ctx::core::execution_lifecycle::StageDisposition::Skipped("not entitled"),
1108 );
1109 }
1110 let Some(PreparedCallResult::Ready(call)) = self.prepared.as_mut() else {
1111 return Ok(
1112 lean_ctx::core::execution_lifecycle::StageDisposition::Skipped(
1113 "admission returned a terminal result",
1114 ),
1115 );
1116 };
1117 *self.server.task_envelope.write().await = Some(context.envelope.clone());
1118 call.decision_context = Some(context.clone());
1119 let (disposition, handoff) = kernel::plan(self.server, call, context).await;
1120 call.kernel_handoff = handoff;
1121 Ok(disposition)
1122 }
1123
1124 async fn dispatch_primitive(
1125 &mut self,
1126 context: &lean_ctx::core::execution_lifecycle::TaskContext,
1127 ) -> Result<
1128 (
1129 Self::Primitive,
1130 lean_ctx::core::execution_lifecycle::StageDisposition,
1131 ),
1132 Self::Error,
1133 > {
1134 match self.prepared.take().expect("MCP admission consumed once") {
1135 PreparedCallResult::Terminal(result, reason) => Ok((
1136 McpDispatched::Terminal(result, reason),
1137 lean_ctx::core::execution_lifecycle::StageDisposition::Applied,
1138 )),
1139 PreparedCallResult::Cached(result) => Ok((
1140 McpDispatched::Terminal(result, "response cache hit"),
1141 lean_ctx::core::execution_lifecycle::StageDisposition::Applied,
1142 )),
1143 PreparedCallResult::Ready(call) => {
1144 let (guard_name, guard_args) =
1148 crate::tools::registered::ctx_call::resolve(&call.name, call.args.as_ref())?;
1149 let audit_agent = self.server.audit_agent_id().await;
1150 if let Some(mut denied) =
1151 LeanCtxServer::guard_role_and_policy(&guard_name, &audit_agent).or_else(|| {
1152 LeanCtxServer::guard_egress(&guard_name, guard_args.as_ref(), &audit_agent)
1153 })
1154 {
1155 if crate::server::dynamic_tools::INTERNAL_HOST_TOOLS
1156 .contains(&guard_name.as_str())
1157 {
1158 denied = host_hook_refusal(denied);
1159 }
1160 return Ok((
1161 McpDispatched::Terminal(denied, "policy changed before dispatch"),
1162 lean_ctx::core::execution_lifecycle::StageDisposition::Applied,
1163 ));
1164 }
1165 let shell_command = (guard_name == "ctx_shell")
1168 .then(|| {
1169 guard_args
1170 .as_ref()
1171 .and_then(|args| args.get("command"))
1172 .and_then(Value::as_str)
1173 })
1174 .flatten();
1175 let execute_items = (guard_name == "ctx_execute")
1178 .then(|| {
1179 guard_args
1180 .as_ref()
1181 .map(crate::server::shell_approval::execute_items)
1182 })
1183 .flatten();
1184 let approval = match (shell_command, execute_items) {
1185 (Some(command), _) => Some(self.server.shell_approval(command).await),
1186 (None, Some(items)) => Some(self.server.execute_approval(&items).await),
1187 (None, None) => None,
1188 };
1189 let shell_grant: Arc<[String]> = match approval {
1190 Some(outcome) => match outcome {
1191 crate::server::shell_approval::Outcome::Granted(programs) => {
1192 Arc::from(programs)
1193 }
1194 crate::server::shell_approval::Outcome::Refused(message) => {
1195 return Ok((
1196 McpDispatched::Terminal(
1197 CallToolResult::error(vec![ContentBlock::text(message)]),
1198 "shell command not approved",
1199 ),
1200 lean_ctx::core::execution_lifecycle::StageDisposition::Applied,
1201 ));
1202 }
1203 crate::server::shell_approval::Outcome::NotNeeded => Arc::from(Vec::new()),
1204 },
1205 None => Arc::from(Vec::new()),
1206 };
1207 if crate::server::native_receipts::requested(&call.name, call.args.as_ref()) {
1208 self.native_receipt_capture = self
1209 .server
1210 .native_receipt_authority
1211 .as_ref()
1212 .map(|authority| {
1213 Arc::new(crate::server::native_receipts::NativeReceiptCapture::new(
1214 authority.clone(),
1215 context.envelope.clone(),
1216 ))
1217 });
1218 }
1219 let dispatch_start = std::time::Instant::now();
1220 let dispatch = super::pipeline::dispatch_primitive(
1221 self.server,
1222 &call.name,
1223 call.args.as_ref(),
1224 call.minimal,
1225 &call.args_fp,
1226 );
1227 let primitive = crate::server::shell_approval::SHELL_GRANT
1228 .scope(
1229 shell_grant,
1230 crate::server::native_receipts::NATIVE_RECEIPT_CAPTURE.scope(
1231 self.native_receipt_capture.clone(),
1232 lean_ctx::core::context_kernel::bridge::runtime::KERNEL_PLANNING_HANDOFF
1233 .scope(call.kernel_handoff.clone(), dispatch),
1234 ),
1235 )
1236 .await;
1237 self.server.record_tool_usage(
1238 &call.name,
1239 dispatch_start,
1240 match &primitive {
1241 Ok(primitive) => primitive.failure(),
1242 Err(error) => Some(super::pipeline::error_failure(error)),
1243 },
1244 );
1245 let primitive = primitive?;
1246 Ok((
1247 McpDispatched::Raw { call, primitive },
1248 lean_ctx::core::execution_lifecycle::StageDisposition::Applied,
1249 ))
1250 }
1251 }
1252 }
1253
1254 async fn reversible_post_process(
1255 &mut self,
1256 _context: &lean_ctx::core::execution_lifecycle::TaskContext,
1257 primitive: Self::Primitive,
1258 ) -> Result<
1259 (
1260 Self::Processed,
1261 lean_ctx::core::execution_lifecycle::StageDisposition,
1262 ),
1263 Self::Error,
1264 > {
1265 match primitive {
1266 McpDispatched::Terminal(result, reason) => Ok((
1267 McpProcessedCall {
1268 result,
1269 pipeline: None,
1270 cache_key: None,
1271 skip_reason: Some(reason),
1272 },
1273 lean_ctx::core::execution_lifecycle::StageDisposition::Skipped(reason),
1274 )),
1275 McpDispatched::Raw { call, primitive } => {
1276 let disposition = match &primitive {
1277 super::pipeline::McpPrimitive::Raw(_) => {
1278 lean_ctx::core::execution_lifecycle::StageDisposition::Applied
1279 }
1280 super::pipeline::McpPrimitive::Terminal(_, reason) => {
1281 lean_ctx::core::execution_lifecycle::StageDisposition::Skipped(reason)
1282 }
1283 };
1284 let mut processed = super::pipeline::reversible_post_process(
1285 self.server,
1286 &call.name,
1287 call.args.as_ref(),
1288 call.minimal,
1289 call.config,
1290 call.machine_readable,
1291 call.auto_context,
1292 call.throttle_warning,
1293 call.decision_context,
1294 primitive,
1295 )
1296 .await?;
1297 if self.native_receipt_capture.is_some() {
1298 processed.freeze_receipt_delivery();
1299 }
1300 Ok((
1301 McpProcessedCall {
1302 result: processed.result.clone(),
1303 pipeline: Some(processed),
1304 cache_key: call.cache_key,
1305 skip_reason: None,
1306 },
1307 disposition,
1308 ))
1309 }
1310 }
1311 }
1312
1313 async fn record_context_ir(
1314 &mut self,
1315 _context: &lean_ctx::core::execution_lifecycle::TaskContext,
1316 processed: &Self::Processed,
1317 ) -> Result<lean_ctx::core::execution_lifecycle::StageDisposition, Self::Error> {
1318 Ok(match processed.pipeline.as_ref() {
1319 Some(pipeline) => super::pipeline::record_context_ir(self.server, pipeline).await,
1320 None => lean_ctx::core::execution_lifecycle::StageDisposition::Skipped(
1321 processed.skip_reason.unwrap_or("terminal result"),
1322 ),
1323 })
1324 }
1325
1326 async fn record_ledger(
1327 &mut self,
1328 _context: &lean_ctx::core::execution_lifecycle::TaskContext,
1329 processed: &Self::Processed,
1330 ) -> Result<lean_ctx::core::execution_lifecycle::StageDisposition, Self::Error> {
1331 if let Some(capture) = &self.native_receipt_capture {
1332 self.native_receipt_metadata = Some(
1333 capture
1334 .publish(&processed.result)
1335 .map_err(|code| ErrorData::internal_error(code, None))?,
1336 );
1337 }
1338 Ok(match processed.pipeline.as_ref() {
1339 Some(pipeline) => super::pipeline::record_ledger(self.server, pipeline).await?,
1340 None => lean_ctx::core::execution_lifecycle::StageDisposition::Skipped(
1341 processed.skip_reason.unwrap_or("terminal result"),
1342 ),
1343 })
1344 }
1345
1346 async fn checkpoint(
1347 &mut self,
1348 _context: &lean_ctx::core::execution_lifecycle::TaskContext,
1349 output: &mut Self::Output,
1350 ) -> Result<lean_ctx::core::execution_lifecycle::StageDisposition, Self::Error> {
1351 let disposition =
1352 super::pipeline::record_checkpoint(self.server, self.checkpoint.take(), output).await;
1353 if let Some(key) = self.pending_cache_key.take() {
1354 let bindable = !lean_ctx::core::context_admission::stored::source_authority_required()
1358 || replay_lineage::bind_cache_entry(&cache_lineage_id(&key));
1359 if bindable && project_only_output() {
1363 cache_call_result(global_response_cache(), key, output);
1364 }
1365 }
1366 Ok(disposition)
1367 }
1368
1369 fn output_from_processed(&mut self, mut processed: Self::Processed) -> Self::Output {
1370 if let Some(pipeline) = processed.pipeline.as_mut() {
1371 self.checkpoint = pipeline.checkpoint.take();
1372 }
1373 self.pending_cache_key = processed.cache_key;
1374 if let Some(receipt) = self.native_receipt_metadata.take() {
1375 processed
1376 .result
1377 .meta
1378 .get_or_insert_with(MetaObject::new)
1379 .0
1380 .insert("canonical_receipt".into(), receipt);
1381 }
1382 processed.result
1383 }
1384
1385 fn observe(
1386 &self,
1387 result: &Result<
1388 Self::Output,
1389 lean_ctx::core::execution_lifecycle::LifecycleRunError<Self::Error>,
1390 >,
1391 ) -> lean_ctx::core::execution_lifecycle::CompletionObservation {
1392 let (output_tokens, success) = result.as_ref().map_or((0, false), |response| {
1393 (
1394 u64::try_from(format!("{response:?}").len() / 4).unwrap_or(u64::MAX),
1395 response.is_error != Some(true),
1396 )
1397 });
1398 lean_ctx::core::execution_lifecycle::CompletionObservation::tool_result(
1399 self.input_tokens,
1400 output_tokens,
1401 "mcp-tool",
1402 success,
1403 )
1404 }
1405}
1406
1407#[cfg(test)]
1408#[path = "guarded_tests.rs"]
1409mod tests;