Skip to main content

lean_ctx_server/server/call_tool/
guarded.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use 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
67/// A gate refusal (role, policy, workflow, loop throttle, budget) on a call to
68/// an internal host hook. The host replaces a native tool's output with the
69/// hook's success body, so the refusal must read as an error: the host then
70/// keeps the original output instead of the block message (#2089).
71fn host_hook_refusal(mut result: CallToolResult) -> CallToolResult {
72    result.is_error = Some(true);
73    result
74}
75
76/// A loop-throttle block as a tool error carrying the detector's message,
77/// like a role or policy denial: the call was refused, not answered.
78/// `None` when the call is not blocked.
79fn loop_throttle_refusal(
80    throttle: &lean_ctx_ext::core::loop_detection::ThrottleResult,
81) -> Option<CallToolResult> {
82    (throttle.level == lean_ctx_ext::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        // A new lifecycle task must execute and bind its own native plan.
127        return None;
128    }
129    // A cached response does not carry the Workspace revision it was served
130    // under; a detached root must be gone on the next call (#2120).
131    if lean_ctx::core::workspace_authority::is_configured() {
132        return None;
133    }
134    // Semantic results include mutable kernel context. Keep its underlying
135    // search caches, but plan/reapply context before caching the whole response.
136    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    // The answer is a function of the files too: an edit between two identical
152    // calls must miss, or the model sees its own change undone and re-reads
153    // the file to resolve the contradiction (benchmark replay: `ctx_search`
154    // after `ctx_patch` returned the pre-edit matches). The stat-only corpus
155    // signature notices edits by any tool; a scan root it cannot fingerprint
156    // is not cached.
157    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
181/// Stat-only signature of the tree a cacheable call scans: its `path`
182/// argument resolved against the project root, else the project root.
183fn 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        // Nothing on disk to drift; the path is part of the key already.
196        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    // The response cache keeps whole tool results without their sources.
203    // Where stored output needs a source authority (policy pack, governed or
204    // sovereign gateway) it is neither read nor filled: an answer cached
205    // before the mode was tightened is not served afterwards.
206    !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
212/// Under protection the response cache is not closed but BOUND: an entry is
213/// stored only together with the lineage of the dispatch that produced it
214/// (a complete captured source set, or an attested source-free output) and
215/// served only while that lineage re-admits under the current policy, role
216/// and project and the gateway policy is unchanged
217/// (`replay_lineage::{bind_cache_entry, cache_entry_current}`). The other
218/// reasons that close the cache — sensitivity floor, redaction switched off
219/// for the role — close the bound cache as well.
220fn 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
226/// Whether the output of the call in scope carries no outside origin (its
227/// ledger and marked parts are empty). Without a capture: unknown, so no.
228fn project_only_output() -> bool {
229    lean_ctx::core::context_admission::capture::current()
230        .is_some_and(|capture| capture.output_origins().is_empty())
231}
232
233/// The lineage record of a response-cache entry.
234fn 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    /// A call keeps the session instance it was bound to once its roots were
285    /// resolved, so a root change while it runs cannot redirect its late
286    /// writes into the next project's session (AP04-G1).
287    pub async fn call_tool_guarded(
288        &self,
289        request: CallToolRequestParams,
290    ) -> Result<CallToolResult, ErrorData> {
291        // One Workspace snapshot per call (#2120): every path check of this
292        // call sees one revision, and the next call sees a detached root gone.
293        let authority = lean_ctx::core::workspace_authority::current();
294        // One rights snapshot per call (process-v1 §9): the request's bound
295        // rights (shared daemon) or this process's LEAN_CTX_RIGHTS_FILE.
296        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        // Background cadence, counted here because this is the one point every
320        // call passes regardless of how it is served: guard denials and
321        // response-cache hits below return before `dispatch_and_post_process`.
322        // It previously hung off `call_count`, which only advances in
323        // `record_checkpoint` — skipped entirely when `minimal_overhead`
324        // (default true) is set. Between the two, the daily telemetry flush
325        // never ran in a default install. The first call sends the day's first
326        // batch, so installs whose sessions stay short are still counted; every
327        // tenth call persists counters and resends the grown day totals once
328        // the aggregate admits it (spacing and daily cap live there).
329        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            // The first and every hundredth call also record the running
335            // version, as the daemon's tick does.
336            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                // Establish client-root authority before early receipt/identity
353                // checks can return, as well as before lifecycle replay lookup.
354                self.resolve_roots_once().await;
355                self.session.pin();
356                let (project, session_id) = {
357                    let session = self.session.read().await;
358                    // The session this call serves: its taint is what the
359                    // release point extends and `session_taint()` reads
360                    // (pz21 §1.7).
361                    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                // One Decision Receipt per call: every admission inside this
366                // call (handler and its read workers) lands in this capture.
367                // It carries the call's ONE policy snapshot, taken here.
368                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                // Under a pack an error leaves as one fixed text. Replaced
384                // before the receipt, so the receipt and its observation name
385                // the bytes that actually leave (AP10-C3).
386                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                // Persisted already (write-through); the session state keeps
397                // the same taint for its own save and for later loads.
398                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                // The receipt is stored before the result leaves (G08).
418                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        // A withheld Cloud tool (release switch off) answers one fixed line
429        // before any lifecycle, ledger or tool state is touched.
430        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            // Includes idempotent replay: stale signer admission is never bypassed.
440            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        // Semantic identity is the actual tool, while replay keys and dispatch
447        // retain the original wrapper request. Invalid envelopes still go
448        // through the normal lifecycle admission/error path.
449        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_ext::core::loop_detection::LoopDetector::fingerprint(&Value::Object(
511                args.clone(),
512            ))
513        });
514        let idempotency_key = raw_idempotency_key.map(|key| {
515            format!("mcp:{session_id}:{agent_id}:{tool_name}:{payload_fingerprint}:{key}")
516        });
517        let client_name = self.client_name.read().await.clone();
518        let release_name = semantic_call
519            .as_ref()
520            .map_or(tool_name.as_str(), |(name, _)| name)
521            .to_owned();
522        let decision_loop_enabled = config.decision_loop.enabled;
523        let lifecycle = lean_ctx::core::execution_lifecycle::ExecutionLifecycle::global();
524        // The replay key is not changed: it only names the lineage record the
525        // dispatch writes and a later replay admission re-authorizes.
526        let replay_key = idempotency_key.clone();
527        let run = lifecycle.run_with_task_identity(
528            lean_ctx::core::execution_lifecycle::ToolRequest {
529                tool_name: semantic_call.map_or(tool_name, |(name, _)| name),
530                query,
531                session_id,
532                agent_id,
533                surface: lean_ctx::core::execution_lifecycle::ToolSurface::Mcp,
534                idempotency_key,
535            },
536            lean_ctx::core::execution_lifecycle::RuntimeContext {
537                client_name: Some(client_name),
538                project_root,
539            },
540            lean_ctx::core::execution_lifecycle::ProductEntitlements {
541                autopilot: decision_loop_enabled,
542                personalized_learning: false,
543            },
544            McpDriver {
545                server: self,
546                request: Some(request),
547                entitlements: Some(McpEntitlements { config }),
548                prepared: None,
549                checkpoint: None,
550                pending_cache_key: None,
551                native_receipt_capture: None,
552                native_receipt_metadata: None,
553                input_tokens,
554            },
555            task_identity,
556        );
557        let outcome = replay_lineage::scope(replay_key, run)
558            .await
559            .map_err(|error| match error {
560                lean_ctx::core::execution_lifecycle::LifecycleRunError::Dispatch(error) => error,
561                lean_ctx::core::execution_lifecycle::LifecycleRunError::ReplayTypeMismatch => {
562                    ErrorData::invalid_request("idempotent execution contract mismatch", None)
563                }
564                lean_ctx::core::execution_lifecycle::LifecycleRunError::Aborted(outcome) => {
565                    ErrorData::internal_error(
566                        format!(
567                            "idempotent execution already terminated: {}",
568                            outcome.accepted_outcome.outcome_id.as_str()
569                        ),
570                        None,
571                    )
572                }
573            });
574        // Both channels pass the release point: an error's message and data
575        // reach the host as surely as a result does (AP10-C1).
576        crate::server::policy_guard::release_outcome(&release_name, outcome)
577    }
578
579    async fn prepare_tool_call(
580        &self,
581        request: CallToolRequestParams,
582        entitlements: McpEntitlements,
583    ) -> Result<PreparedCallResult, ErrorData> {
584        elicitation::increment_call();
585
586        let original_name = request.name.as_ref().to_string();
587        // Plan mode: extract interactionMode before arguments are consumed.
588        let meta_interaction_mode = request
589            .meta
590            .as_ref()
591            .and_then(|m| m.0.get("interactionMode"))
592            .and_then(|v| v.as_str())
593            .and_then(crate::tools::InteractionMode::from_meta_str);
594        let (resolved_name, resolved_args) = crate::tools::registered::ctx_call::normalize_outer(
595            &original_name,
596            request.arguments.as_ref(),
597        )?;
598        let name = resolved_name.as_str();
599        let args = resolved_args.as_ref();
600        let config = entitlements.config;
601        let audit_agent = self.audit_agent_id().await;
602        if let Some(denied) = Self::guard_role_and_policy(name, &audit_agent) {
603            return Ok(PreparedCallResult::Terminal(
604                denied,
605                "role or policy denied",
606            ));
607        }
608        // Cloud `agents.allowed` (ent2-2): the whole session belongs to one
609        // agent, so a refused agent gets no tool at all (ctx_call included).
610        // Fail-closed: a damaged Cloud policy refuses too.
611        {
612            let client_name = self.client_name.read().await.clone();
613            let project_root = self.session.read().await.project_root.clone();
614            if let Some(reason) = lean_ctx::core::policy::cloud_agents::agent_refusal(
615                project_root.as_deref().map(std::path::Path::new),
616                &client_name,
617            ) {
618                tracing::warn!(tool = name, %reason, "agent refused by the team policy");
619                return Ok(PreparedCallResult::Terminal(
620                    CallToolResult::error(vec![ContentBlock::text(format!(
621                        "[POLICY BLOCKED] {reason}. Ask a team admin to allow this agent."
622                    ))]),
623                    "agent not allowed",
624                ));
625            }
626            // N1 `security.require_proxy`: model traffic must go through the
627            // LeanCTX proxy; an agent that cannot be confirmed is refused.
628            if let Some(reason) = lean_ctx::core::policy::cloud_agents::proxy_requirement_refusal(
629                project_root.as_deref().map(std::path::Path::new),
630                &client_name,
631            ) {
632                tracing::warn!(tool = name, %reason, "agent refused by the Cloud policy");
633                return Ok(PreparedCallResult::Terminal(
634                    CallToolResult::error(vec![ContentBlock::text(format!(
635                        "[POLICY BLOCKED] {reason}. Run `lean-ctx proxy enable` and restart \
636                         the agent so its model traffic goes through the LeanCTX proxy."
637                    ))]),
638                    "agent not routed through the proxy",
639                ));
640            }
641        }
642
643        // ctx_call is a meta-dispatcher: the egress DLP and permission-
644        // inheritance gates below must inspect the INNER tool + arguments, or
645        // the universal invoker becomes a policy bypass (#1008 security pass).
646        // Role/rate/workflow gates for the inner tool already run inside the
647        // dispatch layer; these two ran only on the wrapper name before.
648        let inner_call = if name == "ctx_call" {
649            match crate::tools::registered::ctx_call::resolve_inner(args) {
650                Ok(inner) => Some(inner),
651                // Preserve dispatch's soft INVALID_PARAMS contract for clients
652                // that otherwise mistake an argument error for transport failure.
653                Err(error) => {
654                    return Ok(PreparedCallResult::Terminal(
655                        CallToolResult::error(vec![ContentBlock::text(error.message.to_string())]),
656                        "invalid params",
657                    ));
658                }
659            }
660        } else {
661            None
662        };
663        let (guard_name, guard_args): (&str, Option<&serde_json::Map<_, _>>) = match &inner_call {
664            Some((n, a)) => (n.as_str(), a.as_ref()),
665            None => (name, args),
666        };
667        // A wrapper must not plan for a tool that direct admission forbids.
668        // Dispatch still rechecks the inner role/rate/workflow boundaries.
669        if inner_call.is_some() {
670            if let Some(denied) = Self::guard_role_and_policy(guard_name, &audit_agent) {
671                return Ok(PreparedCallResult::Terminal(
672                    denied,
673                    "inner role or policy denied",
674                ));
675            }
676            if let Some(denied) = self.guard_workflow(guard_name).await {
677                return Ok(PreparedCallResult::Terminal(
678                    denied,
679                    "inner workflow denied",
680                ));
681            }
682            if let Some(denied) = self.guard_session_rights(guard_name) {
683                return Ok(PreparedCallResult::Terminal(
684                    denied,
685                    "inner session rights denied",
686                ));
687            }
688        }
689
690        // Plan mode enforcement: update session state and notify on transitions.
691        if let Some(mode) = meta_interaction_mode {
692            let prev = self
693                .interaction_mode
694                .swap(mode as u8, std::sync::atomic::Ordering::Relaxed);
695            if prev != mode as u8 {
696                tracing::info!(
697                    ?mode,
698                    "interaction mode changed — sending tools/list_changed"
699                );
700                if let Some(peer) = self.peer.read().await.as_ref() {
701                    crate::server::notifications::send_tools_list_changed(peer).await;
702                }
703            }
704        }
705
706        // Plan mode guard: block non-readonly tools (including via ctx_call).
707        {
708            use crate::tools::InteractionMode;
709            let current = InteractionMode::from_u8(
710                self.interaction_mode
711                    .load(std::sync::atomic::Ordering::Relaxed),
712            );
713            if current == InteractionMode::Plan {
714                let plan_tools = lean_ctx::core::editor_registry::plan_mode::plan_mode_tools();
715                if !plan_tools.contains(&guard_name) {
716                    let result = CallToolResult::error(vec![ContentBlock::text(format!(
717                        "[PLAN MODE] Tool '{guard_name}' is not available in plan/readonly mode.                          Switch to agent/edit mode to use this tool."
718                    ))]);
719                    return Ok(PreparedCallResult::Terminal(result, "plan mode denied"));
720                }
721            }
722        }
723
724        // Cloud bus control (C5b): `hold`/`stop` pause Cloud tools only,
725        // including via ctx_call; local tools are never gated. The agent id
726        // is copied out first so no lock is held across the file check.
727        let agent = match self.agent_id.read().await.clone() {
728            Some(agent) => Some(agent),
729            None => self.presence_agent_id.read().await.clone(),
730        };
731        if let Some(message) =
732            lean_ctx_cloud::bus::control::tool_refusal(agent.as_deref(), guard_name)
733        {
734            return Ok(PreparedCallResult::Terminal(
735                CallToolResult::error(vec![ContentBlock::text(message)]),
736                "cloud control denied",
737            ));
738        }
739        // A maintainer vetoed this agent's lock or handoff (§3.7.4): its next
740        // ctx_tasks / ctx_agent call says so, once.
741        if let Some(message) = lean_ctx_cloud::bus::veto::take_refusal(agent.as_deref(), guard_name)
742        {
743            return Ok(PreparedCallResult::Terminal(
744                CallToolResult::error(vec![ContentBlock::text(message)]),
745                "cloud veto",
746            ));
747        }
748
749        if let Some(blocked) = Self::guard_egress(guard_name, guard_args, &audit_agent) {
750            return Ok(PreparedCallResult::Terminal(blocked, "egress denied"));
751        }
752
753        if let Some(blocked) = self.guard_workflow(name).await {
754            return Ok(PreparedCallResult::Terminal(blocked, "workflow denied"));
755        }
756
757        if let Some(blocked) = self.guard_session_rights(name) {
758            return Ok(PreparedCallResult::Terminal(
759                blocked,
760                "session rights denied",
761            ));
762        }
763
764        // #990: determine machine-readability *before* the once-per-session
765        // decorations below. A machine-readable invocation (e.g. ctx_outline
766        // format=json) must reach the client byte-exact and parseable, so every
767        // prose decoration and terse compression is suppressed and the pure
768        // pre-decoration body is restored at the end (see the `machine_readable`
769        // guard near the end of this function). Computing it here — not after
770        // dispatch — means such a call also never *consumes* a latched
771        // once-per-session flag (auto-context briefing, rules tip) whose prose
772        // we would then discard, so those surface on the next human-facing call.
773        //
774        // `ctx_call` is a meta-dispatcher: the contract belongs to its *inner*
775        // tool + inner arguments, not to ctx_call itself. Unwrap one level so
776        // JSON reached via the lazy `ctx_call` path (the default advertised
777        // surface, where ctx_outline is not a top-level tool) is just as
778        // byte-exact as a direct call. This also covers JSON error envelopes
779        // from the early rate-limit path, which the first-call auto-context
780        // briefing would otherwise corrupt.
781        let machine_readable = self
782            .registry
783            .as_ref()
784            .and_then(|registry| registry.get_arc(guard_name))
785            .is_some_and(|tool| tool.produces_machine_readable(guard_args));
786
787        // Skip the session wake-up briefing for machine-readable calls: the
788        // wake-up briefing latches `session_briefed` via compare-exchange, so calling
789        // it here would burn the once-per-session slot for a briefing we then
790        // throw away. Deferring keeps the briefing intact for the next call.
791        let args_fp = args
792            .map(|a| {
793                lean_ctx_ext::core::loop_detection::LoopDetector::fingerprint(
794                    &serde_json::Value::Object(a.clone()),
795                )
796            })
797            .unwrap_or_default();
798        let throttle_result = {
799            let semantic_fp = guard_args
800                .map(|args| {
801                    lean_ctx_ext::core::loop_detection::LoopDetector::fingerprint(&Value::Object(
802                        args.clone(),
803                    ))
804                })
805                .unwrap_or_default();
806            let fp = &semantic_fp;
807            let detector_timeout = tokio::time::timeout(
808                std::time::Duration::from_secs(3),
809                self.loop_detector.write(),
810            )
811            .await;
812            if crate::server::dynamic_tools::INTERNAL_HOST_TOOLS.contains(&guard_name) {
813                // A host hook shapes output of a native call the agent already
814                // made; repeating `cargo test` is not a lean-ctx loop (#2089).
815                lean_ctx_ext::core::loop_detection::ThrottleResult::default()
816            } else if let Ok(mut detector) = detector_timeout {
817                let is_search =
818                    lean_ctx_ext::core::loop_detection::LoopDetector::is_search_tool(guard_name);
819                let is_search_shell = guard_name == "ctx_shell" && {
820                    let cmd = guard_args
821                        .and_then(|a| a.get("command"))
822                        .and_then(|v| v.as_str())
823                        .unwrap_or("");
824                    lean_ctx_ext::core::loop_detection::LoopDetector::is_search_shell_command(cmd)
825                };
826
827                if is_search || is_search_shell {
828                    let search_pattern = guard_args.and_then(|a| {
829                        a.get("pattern")
830                            .or_else(|| a.get("query"))
831                            .and_then(|v| v.as_str())
832                    });
833                    let shell_pattern = if is_search_shell {
834                        guard_args
835                            .and_then(|a| a.get("command"))
836                            .and_then(|v| v.as_str())
837                            .and_then(helpers::extract_search_pattern_from_command)
838                    } else {
839                        None
840                    };
841                    let pat = search_pattern.or(shell_pattern.as_deref());
842                    detector.record_search(guard_name, fp, pat)
843                } else {
844                    detector.record_call(guard_name, fp)
845                }
846            } else {
847                tracing::warn!("pre-dispatch: loop_detector write-lock timeout (3s), skipping");
848                lean_ctx_ext::core::loop_detection::ThrottleResult::default()
849            }
850        };
851
852        if let Some(result) = loop_throttle_refusal(&throttle_result) {
853            return Ok(PreparedCallResult::Terminal(
854                result,
855                "loop throttle blocked",
856            ));
857        }
858
859        let throttle_warning = if throttle_result.level
860            == lean_ctx_ext::core::loop_detection::ThrottleLevel::Reduced
861        {
862            throttle_result.message.clone()
863        } else {
864            None
865        };
866
867        // IDE permission inheritance: when enabled, mirror the host IDE's
868        // bash/read/edit/grep permission rules onto the matching lean-ctx tool so
869        // e.g. `ctx_shell` honors a `rm *: ask` rule instead of bypassing it.
870        // Gated on the cheap effective() check so the default (off) pays no lock
871        // cost on the hot path. Checks the ctx_call-unwrapped inner tool (#1008)
872        // so the invoker cannot side-step an IDE deny.
873        if config.permission_inheritance_effective()
874            == lean_ctx::core::config::PermissionInheritance::On
875        {
876            let client_name = self.client_name.read().await.clone();
877            let project_root = self.session.read().await.project_root.clone();
878            let perm = permission_inheritance::check(
879                &client_name,
880                guard_name,
881                guard_args,
882                project_root.as_deref(),
883                &config,
884            );
885            if let Some(blocked) = permission_inheritance::into_call_tool_result(&perm) {
886                tracing::warn!(tool = guard_name, "held back by IDE permission inheritance");
887                return Ok(PreparedCallResult::Terminal(
888                    blocked,
889                    "permission inheritance denied",
890                ));
891            }
892        }
893
894        let project_root = self
895            .session
896            .read()
897            .await
898            .project_root
899            .clone()
900            .unwrap_or_default();
901        // A cached answer is egress too: never served while a policy pack or
902        // the sensitivity floor could withhold what it contains.
903        let bound_cache = bound_cache_allowed(&config);
904        let cache_key = (bound_cache || cache_allowed_for_current_egress(&config))
905            .then(|| response_cache_key(name, args, &project_root))
906            .flatten();
907        let call_start = std::time::Instant::now();
908        if let Some(cached) = cache_key
909            .as_ref()
910            // Under protection a hit needs a lineage that re-admits now.
911            .filter(|key| {
912                !bound_cache || replay_lineage::cache_entry_current(&cache_lineage_id(key))
913            })
914            .and_then(|key| cached_call_result(global_response_cache(), key))
915        {
916            self.record_tool_usage(
917                name,
918                call_start,
919                super::pipeline::result_failure(&cached, ""),
920            );
921            return Ok(PreparedCallResult::Cached(cached));
922        }
923
924        Ok(PreparedCallResult::Ready(Box::new(PreparedMcpCall {
925            name: name.to_owned(),
926            args: args.cloned(),
927            minimal: false,
928            config,
929            machine_readable,
930            auto_context: None,
931            throttle_warning,
932            args_fp,
933            decision_context: None,
934            kernel_handoff:
935                lean_ctx::core::context_kernel::bridge::runtime::KernelPlanningHandoff::Suppressed,
936            cache_key,
937        })))
938    }
939
940    /// Feed the daily telemetry aggregate. Only registered tools are counted,
941    /// under the registry's own name; calls stopped by a guard never reach
942    /// here and are not usage. A failure carries only its class and template.
943    fn record_tool_usage(
944        &self,
945        name: &str,
946        started: std::time::Instant,
947        failure: Option<lean_ctx::core::telemetry_failure::Failure>,
948    ) {
949        let Some(tool) = self
950            .registry
951            .as_ref()
952            .and_then(|registry| registry.static_name(name))
953        else {
954            return;
955        };
956        let latency_us = u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX);
957        lean_ctx::core::telemetry::global_metrics()
958            .record_named_tool_failure(tool, latency_us, failure);
959    }
960}
961
962#[async_trait::async_trait]
963impl lean_ctx::core::execution_lifecycle::ExecutionDriver for McpDriver<'_> {
964    type Primitive = McpDispatched;
965    type Processed = McpProcessedCall;
966    type Output = CallToolResult;
967    type Error = ErrorData;
968
969    async fn identify_caller(
970        &mut self,
971        _context: &lean_ctx::core::execution_lifecycle::TaskContext,
972    ) -> Result<lean_ctx::core::execution_lifecycle::StageDisposition, Self::Error> {
973        self.server
974            .ensure_session_presence()
975            .await
976            .map_err(|error| {
977                ErrorData::internal_error(
978                    format!("agent bus registration is required before tool execution: {error}"),
979                    None,
980                )
981            })?;
982        self.server.check_idle_expiry().await;
983        Ok(lean_ctx::core::execution_lifecycle::StageDisposition::Applied)
984    }
985
986    async fn resolve_workspace(
987        &mut self,
988        _context: &lean_ctx::core::execution_lifecycle::TaskContext,
989    ) -> Result<lean_ctx::core::execution_lifecycle::StageDisposition, Self::Error> {
990        self.server.resolve_roots_once().await;
991        let project = self.server.session.read().await.project_root.clone();
992        lean_ctx::core::policy::runtime::bind_request_project(project.as_deref());
993        Ok(lean_ctx::core::execution_lifecycle::StageDisposition::Applied)
994    }
995
996    async fn resolve_entitlements(
997        &mut self,
998        _context: &lean_ctx::core::execution_lifecycle::TaskContext,
999    ) -> Result<lean_ctx::core::execution_lifecycle::StageDisposition, Self::Error> {
1000        if self.entitlements.is_none() {
1001            return Err(ErrorData::internal_error(
1002                "MCP entitlements were not resolved",
1003                None,
1004            ));
1005        }
1006        Ok(lean_ctx::core::execution_lifecycle::StageDisposition::Applied)
1007    }
1008
1009    async fn apply_security_boundaries(
1010        &mut self,
1011        _context: &lean_ctx::core::execution_lifecycle::TaskContext,
1012    ) -> Result<lean_ctx::core::execution_lifecycle::StageDisposition, Self::Error> {
1013        let request = self.request.take().expect("MCP request consumed once");
1014        let entitlements = self
1015            .entitlements
1016            .take()
1017            .expect("MCP entitlements consumed once");
1018        let host_hook = crate::server::dynamic_tools::targets_internal_host_tool(
1019            request.name.as_ref(),
1020            request.arguments.as_ref(),
1021        );
1022        let prepared = self.server.prepare_tool_call(request, entitlements).await?;
1023        self.prepared = Some(match prepared {
1024            PreparedCallResult::Terminal(result, reason) if host_hook => {
1025                PreparedCallResult::Terminal(host_hook_refusal(result), reason)
1026            }
1027            other => other,
1028        });
1029        Ok(lean_ctx::core::execution_lifecycle::StageDisposition::Applied)
1030    }
1031
1032    async fn validate_cached_replay(
1033        &mut self,
1034        context: &lean_ctx::core::execution_lifecycle::TaskContext,
1035    ) -> Result<Option<Self::Output>, Self::Error> {
1036        self.identify_caller(context).await?;
1037        self.resolve_workspace(context).await?;
1038        self.resolve_entitlements(context).await?;
1039        self.apply_security_boundaries(context).await?;
1040        // Replays revalidate admission only. Context gathering/planning already
1041        // belongs to the cached execution and must not run a second time.
1042        // A current admission denial wins; otherwise the stored output is
1043        // returned only while every source it was derived from is still
1044        // authorized. Loss of rights yields a typed denial — the completed
1045        // operation is never executed again.
1046        Ok(self
1047            .prepared
1048            .take()
1049            .expect("MCP replay admission consumed once")
1050            .into_replay_override()
1051            .or_else(replay_lineage::denial))
1052    }
1053
1054    async fn gather_context_strategy(
1055        &mut self,
1056        context: &lean_ctx::core::execution_lifecycle::TaskContext,
1057    ) -> Result<lean_ctx::core::execution_lifecycle::StageDisposition, Self::Error> {
1058        let Some(PreparedCallResult::Ready(call)) = self.prepared.as_mut() else {
1059            return Ok(
1060                lean_ctx::core::execution_lifecycle::StageDisposition::Skipped(
1061                    "admission returned a terminal result",
1062                ),
1063            );
1064        };
1065        *self.server.task_envelope.write().await = Some(context.envelope.clone());
1066        call.minimal = call.config.minimal_overhead_effective();
1067        // The briefing goes only to `ctx_session` load/status; every other
1068        // result stays free of per-run session text (#498).
1069        if !call.machine_readable {
1070            let (task, project_root) = {
1071                let session = self.server.session.read().await;
1072                (
1073                    session.task.as_ref().map(|task| task.description.clone()),
1074                    session.project_root.clone(),
1075                )
1076            };
1077            if !crate::tools::autonomy::delivers_session_briefing(&call.name, call.args.as_ref()) {
1078                crate::tools::autonomy::apply_auto_load_packages_once(
1079                    &self.server.autonomy,
1080                    project_root.as_deref(),
1081                );
1082                return Ok(lean_ctx::core::execution_lifecycle::StageDisposition::Applied);
1083            }
1084            // Built from this caller's own session instance only (I07/S03).
1085            call.auto_context = lean_ctx::core::session::caller::scope(
1086                Some(self.server.session.instance()),
1087                || {
1088                    crate::tools::autonomy::session_wakeup_briefing(
1089                        &self.server.autonomy,
1090                        &call.name,
1091                        task.as_deref(),
1092                        project_root.as_deref(),
1093                    )
1094                },
1095            );
1096        }
1097        Ok(lean_ctx::core::execution_lifecycle::StageDisposition::Applied)
1098    }
1099
1100    async fn ask_autopilot(
1101        &mut self,
1102        context: &lean_ctx::core::execution_lifecycle::TaskContext,
1103    ) -> Result<lean_ctx::core::execution_lifecycle::StageDisposition, Self::Error> {
1104        if !context.entitlements.autopilot {
1105            if let Some(PreparedCallResult::Ready(call)) = self.prepared.as_mut() {
1106                call.kernel_handoff =
1107                    lean_ctx::core::context_kernel::bridge::runtime::KernelPlanningHandoff::Suppressed;
1108            }
1109            return Ok(
1110                lean_ctx::core::execution_lifecycle::StageDisposition::Skipped("not entitled"),
1111            );
1112        }
1113        let Some(PreparedCallResult::Ready(call)) = self.prepared.as_mut() else {
1114            return Ok(
1115                lean_ctx::core::execution_lifecycle::StageDisposition::Skipped(
1116                    "admission returned a terminal result",
1117                ),
1118            );
1119        };
1120        *self.server.task_envelope.write().await = Some(context.envelope.clone());
1121        call.decision_context = Some(context.clone());
1122        let (disposition, handoff) = kernel::plan(self.server, call, context).await;
1123        call.kernel_handoff = handoff;
1124        Ok(disposition)
1125    }
1126
1127    async fn dispatch_primitive(
1128        &mut self,
1129        context: &lean_ctx::core::execution_lifecycle::TaskContext,
1130    ) -> Result<
1131        (
1132            Self::Primitive,
1133            lean_ctx::core::execution_lifecycle::StageDisposition,
1134        ),
1135        Self::Error,
1136    > {
1137        match self.prepared.take().expect("MCP admission consumed once") {
1138            PreparedCallResult::Terminal(result, reason) => Ok((
1139                McpDispatched::Terminal(result, reason),
1140                lean_ctx::core::execution_lifecycle::StageDisposition::Applied,
1141            )),
1142            PreparedCallResult::Cached(result) => Ok((
1143                McpDispatched::Terminal(result, "response cache hit"),
1144                lean_ctx::core::execution_lifecycle::StageDisposition::Applied,
1145            )),
1146            PreparedCallResult::Ready(call) => {
1147                // Context gathering can await locks/services after admission.
1148                // Recheck current tool and egress rules before any primitive,
1149                // including the inner tool carried by ctx_call, is dispatched.
1150                let (guard_name, guard_args) =
1151                    crate::tools::registered::ctx_call::resolve(&call.name, call.args.as_ref())?;
1152                let audit_agent = self.server.audit_agent_id().await;
1153                if let Some(mut denied) =
1154                    LeanCtxServer::guard_role_and_policy(&guard_name, &audit_agent).or_else(|| {
1155                        LeanCtxServer::guard_egress(&guard_name, guard_args.as_ref(), &audit_agent)
1156                    })
1157                {
1158                    if crate::server::dynamic_tools::INTERNAL_HOST_TOOLS
1159                        .contains(&guard_name.as_str())
1160                    {
1161                        denied = host_hook_refusal(denied);
1162                    }
1163                    return Ok((
1164                        McpDispatched::Terminal(denied, "policy changed before dispatch"),
1165                        lean_ctx::core::execution_lifecycle::StageDisposition::Applied,
1166                    ));
1167                }
1168                // A command refused only for unlisted programs is put to the
1169                // user here, after every policy check and before dispatch.
1170                let shell_command = (guard_name == "ctx_shell")
1171                    .then(|| {
1172                        guard_args
1173                            .as_ref()
1174                            .and_then(|args| args.get("command"))
1175                            .and_then(Value::as_str)
1176                    })
1177                    .flatten();
1178                // ctx_execute code in a language other than shell, likewise
1179                // (GHSA-rxv5-4c3x-g4q6).
1180                let execute_items = (guard_name == "ctx_execute")
1181                    .then(|| {
1182                        guard_args
1183                            .as_ref()
1184                            .map(crate::server::shell_approval::execute_items)
1185                    })
1186                    .flatten();
1187                let approval = match (shell_command, execute_items) {
1188                    (Some(command), _) => Some(self.server.ctx_shell_approval(command).await),
1189                    (None, Some(items)) => Some(self.server.execute_approval(&items).await),
1190                    (None, None) => None,
1191                };
1192                let shell_grant: Arc<[String]> = match approval {
1193                    Some(outcome) => match outcome {
1194                        crate::server::shell_approval::Outcome::Granted(programs) => {
1195                            Arc::from(programs)
1196                        }
1197                        crate::server::shell_approval::Outcome::Refused(message) => {
1198                            return Ok((
1199                                McpDispatched::Terminal(
1200                                    CallToolResult::error(vec![ContentBlock::text(message)]),
1201                                    "shell command not approved",
1202                                ),
1203                                lean_ctx::core::execution_lifecycle::StageDisposition::Applied,
1204                            ));
1205                        }
1206                        crate::server::shell_approval::Outcome::NotNeeded => Arc::from(Vec::new()),
1207                    },
1208                    None => Arc::from(Vec::new()),
1209                };
1210                if crate::server::native_receipts::requested(&call.name, call.args.as_ref()) {
1211                    self.native_receipt_capture = self
1212                        .server
1213                        .native_receipt_authority
1214                        .as_ref()
1215                        .map(|authority| {
1216                            Arc::new(crate::server::native_receipts::NativeReceiptCapture::new(
1217                                authority.clone(),
1218                                context.envelope.clone(),
1219                            ))
1220                        });
1221                }
1222                let dispatch_start = std::time::Instant::now();
1223                let dispatch = super::pipeline::dispatch_primitive(
1224                    self.server,
1225                    &call.name,
1226                    call.args.as_ref(),
1227                    call.minimal,
1228                    &call.args_fp,
1229                );
1230                let primitive = crate::server::shell_approval::SHELL_GRANT
1231                    .scope(
1232                        shell_grant,
1233                        crate::server::native_receipts::NATIVE_RECEIPT_CAPTURE.scope(
1234                            self.native_receipt_capture.clone(),
1235                            lean_ctx::core::context_kernel::bridge::runtime::KERNEL_PLANNING_HANDOFF
1236                                .scope(call.kernel_handoff.clone(), dispatch),
1237                        ),
1238                    )
1239                    .await;
1240                self.server.record_tool_usage(
1241                    &call.name,
1242                    dispatch_start,
1243                    match &primitive {
1244                        Ok(primitive) => primitive.failure(),
1245                        Err(error) => Some(super::pipeline::error_failure(error)),
1246                    },
1247                );
1248                let primitive = primitive?;
1249                Ok((
1250                    McpDispatched::Raw { call, primitive },
1251                    lean_ctx::core::execution_lifecycle::StageDisposition::Applied,
1252                ))
1253            }
1254        }
1255    }
1256
1257    async fn reversible_post_process(
1258        &mut self,
1259        _context: &lean_ctx::core::execution_lifecycle::TaskContext,
1260        primitive: Self::Primitive,
1261    ) -> Result<
1262        (
1263            Self::Processed,
1264            lean_ctx::core::execution_lifecycle::StageDisposition,
1265        ),
1266        Self::Error,
1267    > {
1268        match primitive {
1269            McpDispatched::Terminal(result, reason) => Ok((
1270                McpProcessedCall {
1271                    result,
1272                    pipeline: None,
1273                    cache_key: None,
1274                    skip_reason: Some(reason),
1275                },
1276                lean_ctx::core::execution_lifecycle::StageDisposition::Skipped(reason),
1277            )),
1278            McpDispatched::Raw { call, primitive } => {
1279                let disposition = match &primitive {
1280                    super::pipeline::McpPrimitive::Raw(_) => {
1281                        lean_ctx::core::execution_lifecycle::StageDisposition::Applied
1282                    }
1283                    super::pipeline::McpPrimitive::Terminal(_, reason) => {
1284                        lean_ctx::core::execution_lifecycle::StageDisposition::Skipped(reason)
1285                    }
1286                };
1287                let mut processed = super::pipeline::reversible_post_process(
1288                    self.server,
1289                    &call.name,
1290                    call.args.as_ref(),
1291                    call.minimal,
1292                    call.config,
1293                    call.machine_readable,
1294                    call.auto_context,
1295                    call.throttle_warning,
1296                    call.decision_context,
1297                    primitive,
1298                )
1299                .await?;
1300                if self.native_receipt_capture.is_some() {
1301                    processed.freeze_receipt_delivery();
1302                }
1303                Ok((
1304                    McpProcessedCall {
1305                        result: processed.result.clone(),
1306                        pipeline: Some(processed),
1307                        cache_key: call.cache_key,
1308                        skip_reason: None,
1309                    },
1310                    disposition,
1311                ))
1312            }
1313        }
1314    }
1315
1316    async fn record_context_ir(
1317        &mut self,
1318        _context: &lean_ctx::core::execution_lifecycle::TaskContext,
1319        processed: &Self::Processed,
1320    ) -> Result<lean_ctx::core::execution_lifecycle::StageDisposition, Self::Error> {
1321        Ok(match processed.pipeline.as_ref() {
1322            Some(pipeline) => super::pipeline::record_context_ir(self.server, pipeline).await,
1323            None => lean_ctx::core::execution_lifecycle::StageDisposition::Skipped(
1324                processed.skip_reason.unwrap_or("terminal result"),
1325            ),
1326        })
1327    }
1328
1329    async fn record_ledger(
1330        &mut self,
1331        _context: &lean_ctx::core::execution_lifecycle::TaskContext,
1332        processed: &Self::Processed,
1333    ) -> Result<lean_ctx::core::execution_lifecycle::StageDisposition, Self::Error> {
1334        if let Some(capture) = &self.native_receipt_capture {
1335            self.native_receipt_metadata = Some(
1336                capture
1337                    .publish(&processed.result)
1338                    .map_err(|code| ErrorData::internal_error(code, None))?,
1339            );
1340        }
1341        Ok(match processed.pipeline.as_ref() {
1342            Some(pipeline) => super::pipeline::record_ledger(self.server, pipeline).await?,
1343            None => lean_ctx::core::execution_lifecycle::StageDisposition::Skipped(
1344                processed.skip_reason.unwrap_or("terminal result"),
1345            ),
1346        })
1347    }
1348
1349    async fn checkpoint(
1350        &mut self,
1351        _context: &lean_ctx::core::execution_lifecycle::TaskContext,
1352        output: &mut Self::Output,
1353    ) -> Result<lean_ctx::core::execution_lifecycle::StageDisposition, Self::Error> {
1354        let disposition =
1355            super::pipeline::record_checkpoint(self.server, self.checkpoint.take(), output).await;
1356        if let Some(key) = self.pending_cache_key.take() {
1357            // Under protection a result is cached only together with the
1358            // lineage of the dispatch that produced it; unknown lineage is
1359            // not cached at all.
1360            let bindable = !lean_ctx::core::context_admission::stored::source_authority_required()
1361                || replay_lineage::bind_cache_entry(&cache_lineage_id(&key));
1362            // A cache hit is served without a dispatch, so nothing would
1363            // note its outside origins: such a result is never cached
1364            // (pz21 §1.5), in every mode.
1365            if bindable && project_only_output() {
1366                cache_call_result(global_response_cache(), key, output);
1367            }
1368        }
1369        Ok(disposition)
1370    }
1371
1372    fn output_from_processed(&mut self, mut processed: Self::Processed) -> Self::Output {
1373        if let Some(pipeline) = processed.pipeline.as_mut() {
1374            self.checkpoint = pipeline.checkpoint.take();
1375        }
1376        self.pending_cache_key = processed.cache_key;
1377        if let Some(receipt) = self.native_receipt_metadata.take() {
1378            processed
1379                .result
1380                .meta
1381                .get_or_insert_with(MetaObject::new)
1382                .0
1383                .insert("canonical_receipt".into(), receipt);
1384        }
1385        processed.result
1386    }
1387
1388    fn observe(
1389        &self,
1390        result: &Result<
1391            Self::Output,
1392            lean_ctx::core::execution_lifecycle::LifecycleRunError<Self::Error>,
1393        >,
1394    ) -> lean_ctx::core::execution_lifecycle::CompletionObservation {
1395        let (output_tokens, success) = result.as_ref().map_or((0, false), |response| {
1396            (
1397                u64::try_from(format!("{response:?}").len() / 4).unwrap_or(u64::MAX),
1398                response.is_error != Some(true),
1399            )
1400        });
1401        lean_ctx::core::execution_lifecycle::CompletionObservation::tool_result(
1402            self.input_tokens,
1403            output_tokens,
1404            "mcp-tool",
1405            success,
1406        )
1407    }
1408}
1409
1410#[cfg(test)]
1411#[path = "guarded_tests.rs"]
1412mod tests;