Skip to main content

lean_ctx/core/
server_capabilities.rs

1//! `GET /v1/capabilities` — runtime discovery of what this lean-ctx instance
2//! supports, so any client (any language) can branch on real features instead
3//! of trial calls. The HTTP route lives in `http_server`; the payload builder
4//! lives here so it stays compiled (and drift-tested) without the
5//! `http-server` feature.
6//!
7//! Contract: `docs/contracts/capabilities-contract-v1.md`. The set of
8//! [`TOP_LEVEL_KEYS`] is the stable contract surface and is bound to that doc
9//! by `tests/capabilities_contract_up_to_date.rs`.
10//!
11//! Not to be confused with [`crate::core::capabilities`], which models RBAC
12//! permissions (`fs:read`, …). This module describes *server* capabilities.
13
14use serde_json::{json, Value};
15
16use crate::core::contracts::{status_kv, versions_kv, CAPABILITIES_CONTRACT_VERSION};
17
18/// Stable, documented top-level keys of the capabilities document.
19pub const TOP_LEVEL_KEYS: [&str; 11] = [
20    "contract_version",
21    "server",
22    "plane",
23    "transports",
24    "presets",
25    "read_modes",
26    "tools",
27    "features",
28    "extensions",
29    "contracts",
30    "contract_status",
31];
32
33/// Build the capabilities document for this running instance.
34pub fn capabilities_value() -> Value {
35    let manifest = crate::core::mcp_manifest::manifest_value();
36    let tool_names = tool_names(&manifest);
37    let read_modes = manifest.get("read_modes").cloned().unwrap_or(Value::Null);
38    let active_persona =
39        crate::core::persona::Persona::resolve(&crate::core::config::Config::load());
40
41    json!({
42        "contract_version": CAPABILITIES_CONTRACT_VERSION,
43        "server": {
44            "name": "lean-ctx",
45            "version": env!("CARGO_PKG_VERSION"),
46            "persona": active_persona.name,
47        },
48        "plane": "personal",
49        "transports": ["stdio-mcp", "http-mcp", "rest", "sse"],
50        "presets": crate::core::persona::Persona::builtin_names(),
51        "read_modes": read_modes,
52        "tools": {
53            "total": tool_names.len(),
54            "names": tool_names,
55        },
56        "features": features(),
57        "extensions": extensions(),
58        "contracts": versions_kv(),
59        // Stability per contract document (frozen|stable|experimental) so
60        // clients can check compatibility before building against a surface
61        // (GL #394). Additive: existing consumers are unaffected.
62        "contract_status": status_kv(),
63    })
64}
65
66fn tool_names(manifest: &Value) -> Vec<String> {
67    manifest
68        .get("tools")
69        .and_then(|t| t.get("granular"))
70        .and_then(|g| g.as_array())
71        .map(|arr| {
72            arr.iter()
73                .filter_map(|t| t.get("name").and_then(|n| n.as_str()).map(String::from))
74                .collect()
75        })
76        .unwrap_or_default()
77}
78
79/// Always-on local capabilities — free, ungated, unconditionally available in
80/// every build. The heart of the Local-Free Invariant (RFC §6): these must
81/// never depend on an account, license, or plan.
82pub const LOCAL_ALWAYS_ON_FEATURES: &[&str] = &[
83    "compression",
84    "caching",
85    "knowledge",
86    "session",
87    "gateway",
88    "sensitivity_floor",
89    "savings_ledger",
90    "audit_trail",
91];
92
93/// Local capabilities that are free but gated by *compilation* only (Cargo
94/// features) — never by account/license/plan.
95pub const LOCAL_OPTIONAL_FEATURES: &[&str] = &[
96    "ast_compression",
97    "semantic_search",
98    "http_server",
99    "wasm_runtime",
100];
101
102/// Commercial-plane capabilities — additive, opt-in, and never required for any
103/// local feature. Compiled in via opt-in Cargo features.
104pub const COMMERCIAL_PLANE_FEATURES: &[&str] = &["team_server", "cloud_server"];
105
106/// Always-on capabilities plus compiled-in feature flags. Booleans reflect what
107/// this binary can actually do.
108fn features() -> Value {
109    json!({
110        "compression": true,
111        "caching": true,
112        "knowledge": true,
113        "session": true,
114        "gateway": true,
115        "sensitivity_floor": true,
116        "savings_ledger": true,
117        "audit_trail": true,
118        "ast_compression": cfg!(feature = "tree-sitter"),
119        "semantic_search": cfg!(feature = "embeddings"),
120        "http_server": cfg!(feature = "http-server"),
121        "wasm_runtime": cfg!(feature = "wasm"),
122        "team_server": cfg!(feature = "team-server"),
123        "cloud_server": cfg!(feature = "cloud-server"),
124    })
125}
126
127/// Runtime-discovered extensions: installed plugins plus the registered
128/// read-modes / compressors / chunkers (EPIC 12.9). The sandboxed extension
129/// runtime (EPIC 12.8) expands what registers here.
130fn extensions() -> Value {
131    let plugins = crate::core::plugins::PluginManager::with_registry(|reg| {
132        reg.enabled_plugins()
133            .iter()
134            .map(|p| {
135                json!({
136                    "name": p.manifest.plugin.name,
137                    "version": p.manifest.plugin.version,
138                    "permissions": p.manifest.trust.policy().declared_permissions(),
139                })
140            })
141            .collect::<Vec<_>>()
142    })
143    .unwrap_or_default();
144
145    let (read_modes, compressors, chunkers) = crate::core::extension_registry::global()
146        .read()
147        .map(|r| (r.read_mode_names(), r.compressor_names(), r.chunker_names()))
148        .unwrap_or_default();
149
150    let tools: Vec<Value> = crate::core::plugins::PluginManager::tool_specs()
151        .iter()
152        .map(|t| json!({ "name": t.name, "plugin": t.plugin_name }))
153        .collect();
154
155    json!({
156        "plugins": plugins,
157        "tools": tools,
158        "read_modes": read_modes,
159        "compressors": compressors,
160        "chunkers": chunkers,
161    })
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    #[test]
169    fn payload_has_exactly_documented_top_level_keys() {
170        let v = capabilities_value();
171        let obj = v.as_object().expect("capabilities is an object");
172        let mut keys: Vec<&str> = obj.keys().map(String::as_str).collect();
173        keys.sort_unstable();
174        let mut expected: Vec<&str> = TOP_LEVEL_KEYS.to_vec();
175        expected.sort_unstable();
176        assert_eq!(keys, expected, "top-level keys drifted from TOP_LEVEL_KEYS");
177    }
178
179    #[test]
180    fn contract_version_matches_constant() {
181        let v = capabilities_value();
182        assert_eq!(v["contract_version"], json!(CAPABILITIES_CONTRACT_VERSION));
183    }
184
185    #[test]
186    fn lists_real_tools_and_read_modes() {
187        let v = capabilities_value();
188        assert!(
189            v["tools"]["total"].as_u64().unwrap_or(0) > 0,
190            "expected at least one tool"
191        );
192        assert!(v["read_modes"]["modes"].is_array());
193    }
194
195    #[test]
196    fn extensions_expose_registry_builtins() {
197        let v = capabilities_value();
198        let ext = &v["extensions"];
199        assert!(ext["plugins"].is_array());
200        let compressors = ext["compressors"].as_array().expect("compressors array");
201        assert!(compressors.iter().any(|c| c == "identity"));
202        assert!(ext["read_modes"]
203            .as_array()
204            .is_some_and(|a| a.iter().any(|m| m == "full")));
205        assert!(ext["chunkers"]
206            .as_array()
207            .is_some_and(|a| a.iter().any(|c| c == "lines")));
208    }
209
210    #[test]
211    fn feature_keys_partition_into_local_and_commercial() {
212        // Every advertised feature must be classified as local (always-on or
213        // compile-optional) or commercial — no unclassified flag. This keeps the
214        // Local-Free Invariant lists honest as features are added.
215        let v = capabilities_value();
216        let keys: std::collections::BTreeSet<String> = v["features"]
217            .as_object()
218            .expect("features object")
219            .keys()
220            .cloned()
221            .collect();
222        let mut classified: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
223        for k in LOCAL_ALWAYS_ON_FEATURES
224            .iter()
225            .chain(LOCAL_OPTIONAL_FEATURES)
226            .chain(COMMERCIAL_PLANE_FEATURES)
227        {
228            classified.insert((*k).to_string());
229        }
230        assert_eq!(
231            keys, classified,
232            "every feature must be classified local vs commercial (Local-Free Invariant)"
233        );
234    }
235
236    #[test]
237    fn local_always_on_features_are_unconditionally_true() {
238        let v = capabilities_value();
239        for key in LOCAL_ALWAYS_ON_FEATURES {
240            assert_eq!(
241                v["features"][key],
242                json!(true),
243                "local capability '{key}' must be free + always on"
244            );
245        }
246    }
247
248    #[test]
249    fn reports_compiled_features() {
250        let v = capabilities_value();
251        // Always-on capabilities are unconditionally true.
252        assert_eq!(v["features"]["compression"], json!(true));
253        assert_eq!(v["features"]["savings_ledger"], json!(true));
254        // Feature-gated flags mirror the compile-time cfg.
255        assert_eq!(
256            v["features"]["semantic_search"],
257            json!(cfg!(feature = "embeddings"))
258        );
259    }
260}