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::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        // 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::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        // The replay key is not changed: it only names the lineage record the
523        // dispatch writes and a later replay admission re-authorizes.
524        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        // Both channels pass the release point: an error's message and data
573        // reach the host as surely as a result does (AP10-C1).
574        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        // Plan mode: extract interactionMode before arguments are consumed.
586        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        // Cloud `agents.allowed` (ent2-2): the whole session belongs to one
607        // agent, so a refused agent gets no tool at all (ctx_call included).
608        // Fail-closed: a damaged Cloud policy refuses too.
609        {
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            // N1 `security.require_proxy`: model traffic must go through the
625            // LeanCTX proxy; an agent that cannot be confirmed is refused.
626            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        // ctx_call is a meta-dispatcher: the egress DLP and permission-
642        // inheritance gates below must inspect the INNER tool + arguments, or
643        // the universal invoker becomes a policy bypass (#1008 security pass).
644        // Role/rate/workflow gates for the inner tool already run inside the
645        // dispatch layer; these two ran only on the wrapper name before.
646        let inner_call = if name == "ctx_call" {
647            match crate::tools::registered::ctx_call::resolve_inner(args) {
648                Ok(inner) => Some(inner),
649                // Preserve dispatch's soft INVALID_PARAMS contract for clients
650                // that otherwise mistake an argument error for transport failure.
651                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        // A wrapper must not plan for a tool that direct admission forbids.
666        // Dispatch still rechecks the inner role/rate/workflow boundaries.
667        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        // Plan mode enforcement: update session state and notify on transitions.
689        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        // Plan mode guard: block non-readonly tools (including via ctx_call).
705        {
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        // Cloud bus control (C5b): `hold`/`stop` pause Cloud tools only,
723        // including via ctx_call; local tools are never gated. The agent id
724        // is copied out first so no lock is held across the file check.
725        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        // A maintainer vetoed this agent's lock or handoff (§3.7.4): its next
738        // ctx_tasks / ctx_agent call says so, once.
739        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        // #990: determine machine-readability *before* the once-per-session
763        // decorations below. A machine-readable invocation (e.g. ctx_outline
764        // format=json) must reach the client byte-exact and parseable, so every
765        // prose decoration and terse compression is suppressed and the pure
766        // pre-decoration body is restored at the end (see the `machine_readable`
767        // guard near the end of this function). Computing it here — not after
768        // dispatch — means such a call also never *consumes* a latched
769        // once-per-session flag (auto-context briefing, rules tip) whose prose
770        // we would then discard, so those surface on the next human-facing call.
771        //
772        // `ctx_call` is a meta-dispatcher: the contract belongs to its *inner*
773        // tool + inner arguments, not to ctx_call itself. Unwrap one level so
774        // JSON reached via the lazy `ctx_call` path (the default advertised
775        // surface, where ctx_outline is not a top-level tool) is just as
776        // byte-exact as a direct call. This also covers JSON error envelopes
777        // from the early rate-limit path, which the first-call auto-context
778        // briefing would otherwise corrupt.
779        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        // Skip the session wake-up briefing for machine-readable calls: the
786        // wake-up briefing latches `session_briefed` via compare-exchange, so calling
787        // it here would burn the once-per-session slot for a briefing we then
788        // throw away. Deferring keeps the briefing intact for the next call.
789        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                // A host hook shapes output of a native call the agent already
812                // made; repeating `cargo test` is not a lean-ctx loop (#2089).
813                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        // IDE permission inheritance: when enabled, mirror the host IDE's
865        // bash/read/edit/grep permission rules onto the matching lean-ctx tool so
866        // e.g. `ctx_shell` honors a `rm *: ask` rule instead of bypassing it.
867        // Gated on the cheap effective() check so the default (off) pays no lock
868        // cost on the hot path. Checks the ctx_call-unwrapped inner tool (#1008)
869        // so the invoker cannot side-step an IDE deny.
870        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        // A cached answer is egress too: never served while a policy pack or
899        // the sensitivity floor could withhold what it contains.
900        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            // Under protection a hit needs a lineage that re-admits now.
908            .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    /// Feed the daily telemetry aggregate. Only registered tools are counted,
938    /// under the registry's own name; calls stopped by a guard never reach
939    /// here and are not usage. A failure carries only its class and template.
940    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        // Replays revalidate admission only. Context gathering/planning already
1038        // belongs to the cached execution and must not run a second time.
1039        // A current admission denial wins; otherwise the stored output is
1040        // returned only while every source it was derived from is still
1041        // authorized. Loss of rights yields a typed denial — the completed
1042        // operation is never executed again.
1043        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        // The briefing goes only to `ctx_session` load/status; every other
1065        // result stays free of per-run session text (#498).
1066        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            // Built from this caller's own session instance only (I07/S03).
1082            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                // Context gathering can await locks/services after admission.
1145                // Recheck current tool and egress rules before any primitive,
1146                // including the inner tool carried by ctx_call, is dispatched.
1147                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                // A command refused only for unlisted programs is put to the
1166                // user here, after every policy check and before dispatch.
1167                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                // ctx_execute code in a language other than shell, likewise
1176                // (GHSA-rxv5-4c3x-g4q6).
1177                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            // Under protection a result is cached only together with the
1355            // lineage of the dispatch that produced it; unknown lineage is
1356            // not cached at all.
1357            let bindable = !lean_ctx::core::context_admission::stored::source_authority_required()
1358                || replay_lineage::bind_cache_entry(&cache_lineage_id(&key));
1359            // A cache hit is served without a dispatch, so nothing would
1360            // note its outside origins: such a result is never cached
1361            // (pz21 §1.5), in every mode.
1362            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;