Skip to main content

lean_ctx/core/context_kernel/
mcp_bridge.rs

1//! Unified integration between MCP clients and the context kernel.
2
3use std::sync::{Mutex, MutexGuard, OnceLock};
4use std::time::{SystemTime, UNIX_EPOCH};
5
6use super::client_wiring::OptimizationLevel;
7use super::coverage_class::{self, CoverageClass};
8use super::etpao_live::{EtpaoLive, OutcomeMetrics, RequestMetrics};
9use super::identity::{CallerIdentity, CallerRole, IdentityLedger};
10use super::outcome_signal::{self, OutcomeSignal};
11use super::types::ReceiptOutcome;
12
13static MCP_ETPAO: OnceLock<Mutex<EtpaoLive>> = OnceLock::new();
14static MCP_IDENTITY: OnceLock<Mutex<IdentityLedger>> = OnceLock::new();
15
16const MCP_SESSION_ID: &str = "mcp-session";
17
18/// Information about the MCP client, extracted from the initialize handshake.
19#[derive(Debug, Clone, Default)]
20pub struct McpClientInfo {
21    /// Client application name (e.g. "cursor", "vscode", "zed").
22    pub client_name: String,
23    /// Whether the client declared roots capability.
24    pub supports_roots: bool,
25    /// Whether the client declared sampling capability.
26    pub supports_sampling: bool,
27    /// Number of tools visible to the client.
28    pub tool_count: usize,
29}
30
31/// Data for a single MCP tool call, used to record ETPAO metrics.
32#[derive(Debug, Clone, Default)]
33pub struct McpCallData {
34    /// Name of the tool called.
35    pub tool_name: String,
36    /// Estimated input tokens (tool arguments and context).
37    pub input_tokens: usize,
38    /// Output tokens in the tool result.
39    pub output_tokens: usize,
40    /// Whether this is a retry of a previous call.
41    pub is_retry: bool,
42    /// Sequential call number in the session.
43    pub call_number: usize,
44}
45
46/// Result of kernel processing for an MCP client session.
47#[derive(Debug, Clone)]
48pub struct McpKernelResult {
49    /// Integration coverage detected for the client.
50    pub coverage: CoverageClass,
51    /// Stable machine-readable label for the coverage class.
52    pub coverage_label: &'static str,
53    /// Whether the kernel can directly optimize client context.
54    pub is_addressable: bool,
55    /// Optimization strength appropriate for the client.
56    pub optimization_level: OptimizationLevel,
57    /// Maximum tokens available for MCP tool schemas.
58    pub schema_budget: usize,
59}
60
61/// Aggregate MCP metrics summary.
62#[derive(Debug, Clone, Default)]
63pub struct McpSummary {
64    /// Number of recorded MCP tool calls.
65    pub total_calls: usize,
66    /// Estimated input tokens across all calls.
67    pub total_input_tokens: usize,
68    /// Output tokens across all calls.
69    pub total_output_tokens: usize,
70    /// Calls inferred to have been accepted.
71    pub accepted_calls: usize,
72    /// Effective tokens consumed per accepted outcome.
73    pub etpao: f64,
74    /// Stable coverage label used for recorded MCP calls.
75    pub coverage_label: String,
76}
77
78/// Processes an MCP initialize handshake into kernel policy and budget data.
79#[must_use]
80pub fn process_mcp_context(info: &McpClientInfo) -> McpKernelResult {
81    let coverage = super::mcp_coverage::detect_mcp_coverage(
82        &info.client_name,
83        info.supports_roots,
84        info.supports_sampling,
85    );
86    let profile = super::mcp_coverage::mcp_client_profile(&info.client_name);
87
88    McpKernelResult {
89        coverage,
90        coverage_label: coverage_class::coverage_label(coverage),
91        is_addressable: coverage_class::is_addressable(coverage),
92        optimization_level: optimization_level(coverage),
93        schema_budget: profile.tool_budget.max_schema_tokens,
94    }
95}
96
97/// Records token usage, inferred outcome, and session identity for an MCP call.
98pub fn record_mcp_call(data: &McpCallData) {
99    let call_number = if data.is_retry {
100        data.call_number.max(2)
101    } else {
102        data.call_number
103    };
104    let inferred = outcome_signal::infer_outcome(call_number, data.is_retry, data.output_tokens);
105    let accepted = inferred.outcome == ReceiptOutcome::Accepted;
106
107    lock_etpao().record_request(RequestMetrics {
108        input_tokens: data.input_tokens,
109        output_tokens: data.output_tokens,
110        reasoning_tokens: 0,
111        schema_tokens: 0,
112        cache_write_tokens: 0,
113        retry_count: usize::from(data.is_retry),
114        client_id: MCP_SESSION_ID.to_owned(),
115        coverage_class: CoverageClass::ContextControlled,
116    });
117    lock_etpao().record_outcome(OutcomeMetrics {
118        accepted,
119        quality_score: inferred.confidence,
120        first_pass: inferred.signal == OutcomeSignal::FirstPass,
121        client_id: MCP_SESSION_ID.to_owned(),
122    });
123
124    lock_identity().record(
125        &mcp_identity(),
126        data.input_tokens,
127        data.output_tokens,
128        accepted,
129    );
130}
131
132/// Generate a ContextReceiptV1 from completed MCP tool call data.
133#[must_use]
134pub fn generate_mcp_receipt(
135    plan_id: &str,
136    tool_name: &str,
137    _input_tokens: usize,
138    output_tokens: usize,
139    cache_hit: bool,
140) -> super::types::ContextReceiptV1 {
141    use std::collections::HashMap;
142
143    use super::types::{ContextReceiptV1, ReceiptOutcome};
144
145    ContextReceiptV1 {
146        receipt_id: format!("mcp-{tool_name}-{}", uuid_v4_short()),
147        plan_id: plan_id.to_owned(),
148        task_id: crate::core::task_spine::TaskSpine::task_id(),
149        delivered_tokens: output_tokens,
150        cache_hits: usize::from(cache_hit),
151        cache_misses: usize::from(!cache_hit),
152        // A successful MCP delivery is an Engine/tool fact, not an explicit
153        // host or evaluator judgment about task quality.
154        outcome: ReceiptOutcome::Unknown,
155        quality_signals: vec![],
156        feedback_attribution: HashMap::new(),
157    }
158}
159
160/// Returns the current MCP effective-tokens-per-accepted-outcome value.
161#[must_use]
162pub fn mcp_etpao() -> f64 {
163    lock_etpao().current_etpao()
164}
165
166/// Returns aggregate metrics for all MCP calls recorded in this process.
167#[must_use]
168pub fn mcp_summary() -> McpSummary {
169    let etpao = lock_etpao();
170    let etpao_summary = etpao.summary();
171    let total_calls = etpao.request_count();
172    drop(etpao);
173
174    let identity_summary = lock_identity().summary();
175    McpSummary {
176        total_calls,
177        total_input_tokens: identity_summary.total_tokens,
178        total_output_tokens: identity_summary.total_savings,
179        accepted_calls: etpao_summary.accepted_outcomes,
180        etpao: etpao_summary.etpao,
181        coverage_label: coverage_class::coverage_label(CoverageClass::ContextControlled).to_owned(),
182    }
183}
184
185/// Clears process-wide MCP metrics and identity state.
186pub fn reset_mcp_state() {
187    *lock_etpao() = EtpaoLive::new();
188    *lock_identity() = IdentityLedger::new();
189}
190
191fn optimization_level(coverage: CoverageClass) -> OptimizationLevel {
192    match coverage {
193        CoverageClass::FullInline => OptimizationLevel::Full,
194        CoverageClass::ContextControlled => OptimizationLevel::Partial,
195        CoverageClass::ObserveOnly => OptimizationLevel::ObserveOnly,
196        CoverageClass::Unmanaged => OptimizationLevel::None,
197    }
198}
199
200fn mcp_identity() -> CallerIdentity {
201    CallerIdentity {
202        user_id: Some(MCP_SESSION_ID.to_owned()),
203        role: CallerRole::Agent,
204        session_id: Some(MCP_SESSION_ID.to_owned()),
205        ..CallerIdentity::default()
206    }
207}
208
209fn uuid_v4_short() -> String {
210    SystemTime::now()
211        .duration_since(UNIX_EPOCH)
212        .unwrap_or_default()
213        .as_nanos()
214        .to_string()
215}
216
217fn lock_etpao() -> MutexGuard<'static, EtpaoLive> {
218    MCP_ETPAO
219        .get_or_init(|| Mutex::new(EtpaoLive::new()))
220        .lock()
221        .unwrap_or_else(std::sync::PoisonError::into_inner)
222}
223
224fn lock_identity() -> MutexGuard<'static, IdentityLedger> {
225    MCP_IDENTITY
226        .get_or_init(|| Mutex::new(IdentityLedger::new()))
227        .lock()
228        .unwrap_or_else(std::sync::PoisonError::into_inner)
229}
230
231#[cfg(test)]
232pub mod tests {
233    use std::sync::{Mutex, MutexGuard};
234
235    use super::{
236        McpCallData, McpClientInfo, generate_mcp_receipt, mcp_etpao, mcp_summary,
237        process_mcp_context, record_mcp_call, reset_mcp_state,
238    };
239    use crate::core::context_kernel::coverage_class::CoverageClass;
240    use crate::core::context_kernel::types::ReceiptOutcome;
241
242    static TEST_LOCK: Mutex<()> = Mutex::new(());
243
244    fn test_guard() -> MutexGuard<'static, ()> {
245        TEST_LOCK
246            .lock()
247            .unwrap_or_else(std::sync::PoisonError::into_inner)
248    }
249
250    fn call(number: usize, retry: bool) -> McpCallData {
251        McpCallData {
252            tool_name: "ctx_read".to_owned(),
253            input_tokens: 100,
254            output_tokens: 20,
255            is_retry: retry,
256            call_number: number,
257        }
258    }
259
260    #[test]
261    fn process_cursor_context() {
262        let _guard = test_guard();
263        let result = process_mcp_context(&McpClientInfo {
264            client_name: "cursor".to_owned(),
265            ..McpClientInfo::default()
266        });
267        assert_eq!(result.coverage, CoverageClass::FullInline);
268    }
269
270    #[test]
271    fn process_vscode_context() {
272        let _guard = test_guard();
273        let result = process_mcp_context(&McpClientInfo {
274            client_name: "vscode".to_owned(),
275            ..McpClientInfo::default()
276        });
277        assert_eq!(result.coverage, CoverageClass::ContextControlled);
278    }
279
280    #[test]
281    fn process_unknown_context() {
282        let _guard = test_guard();
283        let result = process_mcp_context(&McpClientInfo {
284            client_name: "unknown".to_owned(),
285            ..McpClientInfo::default()
286        });
287        assert_eq!(result.coverage, CoverageClass::ObserveOnly);
288    }
289
290    #[test]
291    fn record_call_updates_etpao() {
292        let _guard = test_guard();
293        reset_mcp_state();
294        record_mcp_call(&call(1, false));
295        assert!(mcp_etpao() > 0.0);
296    }
297
298    #[test]
299    fn record_retry_is_rejected() {
300        let _guard = test_guard();
301        reset_mcp_state();
302        record_mcp_call(&call(2, true));
303        assert_eq!(mcp_summary().accepted_calls, 0);
304    }
305
306    #[test]
307    fn summary_aggregates() {
308        let _guard = test_guard();
309        reset_mcp_state();
310        for number in 1..=5 {
311            record_mcp_call(&call(number, false));
312        }
313        let summary = mcp_summary();
314        assert_eq!(summary.total_calls, 5);
315        assert_eq!(summary.total_input_tokens, 500);
316        assert_eq!(summary.total_output_tokens, 100);
317    }
318
319    #[test]
320    fn reset_clears() {
321        let _guard = test_guard();
322        reset_mcp_state();
323        record_mcp_call(&call(1, false));
324        reset_mcp_state();
325        assert_eq!(mcp_etpao(), 0.0);
326        assert_eq!(mcp_summary().total_calls, 0);
327    }
328
329    #[test]
330    fn test_generate_mcp_receipt_fields() {
331        let receipt = generate_mcp_receipt("plan-42", "ctx_read", 100, 20, false);
332
333        assert_eq!(receipt.plan_id, "plan-42");
334        assert!(receipt.receipt_id.starts_with("mcp-ctx_read-"));
335        assert_eq!(receipt.delivered_tokens, 20);
336        assert_eq!(receipt.outcome, ReceiptOutcome::Unknown);
337    }
338
339    #[test]
340    fn test_receipt_cache_hit_counting() {
341        let receipt = generate_mcp_receipt("plan-42", "ctx_read", 100, 20, true);
342
343        assert_eq!(receipt.cache_hits, 1);
344        assert_eq!(receipt.cache_misses, 0);
345    }
346
347    #[test]
348    fn test_receipt_cache_miss_counting() {
349        let receipt = generate_mcp_receipt("plan-42", "ctx_read", 100, 20, false);
350
351        assert_eq!(receipt.cache_hits, 0);
352        assert_eq!(receipt.cache_misses, 1);
353    }
354}