Skip to main content

lean_ctx/tools/registered/
ctx_pack.rs

1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::server::tool_trait::{
6    McpTool, ToolContext, ToolOutput, get_bool, get_int, get_str, get_str_array, get_usize,
7};
8use crate::tool_defs::tool_def;
9
10pub struct CtxPackTool;
11
12impl McpTool for CtxPackTool {
13    fn name(&self) -> &'static str {
14        "ctx_pack"
15    }
16
17    fn tool_def(&self) -> Tool {
18        tool_def(
19            "ctx_pack",
20            "WORKFLOW: create -> export -> import -> install for sharing context state.\n\
21            ANTIPATTERN: NOT for ephemeral session save (use ctx_session).\n\
22            Context Package Manager — create, install, manage portable context packages\n\
23            with knowledge, graph, session patterns, and gotchas.\n\
24            Actions: pr, create, list, info, remove, install, export, import, auto_load, summary, bundle.\n\
25            bundle: one budgeted XML document (task-ranked files, signatures, tree) that fits a chat input box.\n\
26            Saves tokens: pre-built context state (avoids re-building).",
27            json!({
28                "type": "object",
29                "properties": {
30                    "action": {
31                        "type": "string",
32                        "enum": ["pr", "create", "list", "info", "remove", "install", "export", "import", "auto_load", "summary", "bundle"],
33                        "description": "Pack action to perform"
34                    },
35                    "path": {
36                        "type": "string",
37                        "description": "Directory or file to bundle (bundle; default: project root)"
38                    },
39                    "limit": {
40                        "type": "string",
41                        "description": "Hard size cap, e.g. 128k, 2M, 32000 (bundle; default 128k)"
42                    },
43                    "unit": {
44                        "type": "string",
45                        "enum": ["chars", "tokens"],
46                        "description": "What limit counts (bundle; default chars)"
47                    },
48                    "intent": {
49                        "type": "string",
50                        "description": "Task the bundle is for; ranks files (bundle; default: session task)"
51                    },
52                    "emit": {
53                        "type": "string",
54                        "enum": ["xml", "plain", "both"],
55                        "description": "xml bundle, plain allocation report, or both (bundle)"
56                    },
57                    "include": {
58                        "type": "array",
59                        "items": { "type": "string" },
60                        "description": "Globs to include (bundle)"
61                    },
62                    "ignore": {
63                        "type": "array",
64                        "items": { "type": "string" },
65                        "description": "Globs to exclude (bundle)"
66                    },
67                    "with_knowledge": {
68                        "type": "array",
69                        "items": { "type": "string" },
70                        "description": "Knowledge categories to append, e.g. decision, architecture, or all (bundle)"
71                    },
72                    "knowledge_limit": {
73                        "type": "integer",
74                        "description": "Max knowledge facts (bundle; default 10)"
75                    },
76                    "with_auto": {
77                        "type": "boolean",
78                        "description": "Also include machine-derived auto:* facts (bundle)"
79                    },
80                    "project_root": {
81                        "type": "string",
82                        "description": "Project root directory"
83                    },
84                    "name": {
85                        "type": "string",
86                        "description": "Package name"
87                    },
88                    "version": {
89                        "type": "string",
90                        "description": "Package version (semver)"
91                    },
92                    "description": {
93                        "type": "string",
94                        "description": "Package description (for create)"
95                    },
96                    "author": {
97                        "type": "string",
98                        "description": "Package author (for create)"
99                    },
100                    "tags": {
101                        "type": "array",
102                        "items": { "type": "string" },
103                        "description": "Tags for categorization (for create)"
104                    },
105                    "layers": {
106                        "type": "array",
107                        "items": { "type": "string" },
108                        "description": "Layers to include: knowledge|graph|session|patterns|gotchas"
109                    },
110                    "level": {
111                        "type": "integer",
112                        "description": "Detail level 1-3 (higher = more detail)"
113                    },
114                    "scope": {
115                        "type": "string",
116                        "description": "Package scope (e.g. @org/name)"
117                    },
118                    "base": {
119                        "type": "string",
120                        "description": "Git base ref for PR diff"
121                    },
122                    "format": {
123                        "type": "string",
124                        "enum": ["markdown", "json"],
125                        "description": "Output format: markdown|json"
126                    },
127                    "depth": {
128                        "type": "integer",
129                        "description": "Impact depth for pr action (default: 3)"
130                    },
131                    "diff": {
132                        "type": "string",
133                        "description": "Git diff --name-status text input"
134                    },
135                    "file": {
136                        "type": "string",
137                        "description": "File path for import/export; bundle output file"
138                    },
139                    "apply": {
140                        "type": "boolean",
141                        "description": "Apply after import (default: false)"
142                    },
143                    "enable": {
144                        "type": "boolean",
145                        "description": "Enable auto-load (default: true)"
146                    }
147                },
148                "required": ["action"],
149                "allOf": [
150                    {
151                        "if": { "properties": { "action": { "const": "create" } }, "required": ["action"] },
152                        "then": { "required": ["action", "name"] }
153                    },
154                    {
155                        "if": { "properties": { "action": { "const": "info" } }, "required": ["action"] },
156                        "then": { "required": ["action", "name"] }
157                    },
158                    {
159                        "if": { "properties": { "action": { "const": "remove" } }, "required": ["action"] },
160                        "then": { "required": ["action", "name"] }
161                    },
162                    {
163                        "if": { "properties": { "action": { "const": "install" } }, "required": ["action"] },
164                        "then": { "required": ["action", "name"] }
165                    },
166                    {
167                        "if": { "properties": { "action": { "const": "export" } }, "required": ["action"] },
168                        "then": { "required": ["action", "name"] }
169                    },
170                    {
171                        "if": { "properties": { "action": { "const": "import" } }, "required": ["action"] },
172                        "then": { "required": ["action", "file"] }
173                    }
174                ]
175            }),
176        )
177    }
178
179    fn handle(
180        &self,
181        args: &Map<String, Value>,
182        ctx: &ToolContext,
183    ) -> Result<ToolOutput, ErrorData> {
184        let action = get_str(args, "action")
185            .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
186
187        let project_root = if let Some(p) = ctx
188            .resolved_path("project_root")
189            .or(ctx.resolved_path("root"))
190        {
191            p.to_string()
192        } else if let Some(err) = ctx.path_error("project_root").or(ctx.path_error("root")) {
193            return Err(ErrorData::invalid_params(
194                format!("project_root: {err}"),
195                None,
196            ));
197        } else {
198            ctx.project_root.clone()
199        };
200
201        let result = match action.as_str() {
202            "pr" => {
203                let base = get_str(args, "base");
204                let format = get_str(args, "format");
205                let depth = get_usize(args, "depth").map(|d| d.min(64));
206                let diff = get_str(args, "diff");
207                crate::tools::ctx_pack::handle(
208                    "pr",
209                    &project_root,
210                    base.as_deref(),
211                    format.as_deref(),
212                    depth,
213                    diff.as_deref(),
214                )
215            }
216            "create" => {
217                let name = get_str(args, "name")
218                    .ok_or_else(|| ErrorData::invalid_params("name is required for create", None))?;
219                let version = get_str(args, "version");
220                let description = get_str(args, "description");
221                let author = get_str(args, "author");
222                let tags = get_str_array(args, "tags");
223                let layers = get_str_array(args, "layers");
224                let level = get_int(args, "level").and_then(|l| u32::try_from(l).ok());
225                let scope = get_str(args, "scope");
226                crate::tools::ctx_pack::handle_create(
227                    &project_root,
228                    &name,
229                    version.as_deref(),
230                    description.as_deref(),
231                    author.as_deref(),
232                    tags.as_deref(),
233                    layers.as_deref(),
234                    level,
235                    scope.as_deref(),
236                )
237            }
238            "list" => crate::tools::ctx_pack::handle_list(),
239            "info" => {
240                let name = get_str(args, "name")
241                    .ok_or_else(|| ErrorData::invalid_params("name is required for info", None))?;
242                let version = get_str(args, "version");
243                crate::tools::ctx_pack::handle_info(&name, version.as_deref())
244            }
245            "remove" => {
246                let name = get_str(args, "name")
247                    .ok_or_else(|| ErrorData::invalid_params("name is required for remove", None))?;
248                let version = get_str(args, "version");
249                crate::tools::ctx_pack::handle_remove(&name, version.as_deref())
250            }
251            "install" => {
252                let name = get_str(args, "name").ok_or_else(|| {
253                    ErrorData::invalid_params("name is required for install", None)
254                })?;
255                let version = get_str(args, "version");
256                crate::tools::ctx_pack::handle_install(&name, version.as_deref(), &project_root)
257            }
258            "export" => {
259                let name = get_str(args, "name").ok_or_else(|| {
260                    ErrorData::invalid_params("name is required for export", None)
261                })?;
262                let version = get_str(args, "version");
263                let file = get_str(args, "file");
264                crate::tools::ctx_pack::handle_export(&name, version.as_deref(), file.as_deref())
265            }
266            "import" => {
267                let file = get_str(args, "file")
268                    .ok_or_else(|| ErrorData::invalid_params("file is required for import", None))?;
269                let apply = get_bool(args, "apply").unwrap_or(false);
270                crate::tools::ctx_pack::handle_import(&file, apply, &project_root)
271            }
272            "auto_load" => {
273                let name = get_str(args, "name");
274                let version = get_str(args, "version");
275                let enable = get_bool(args, "enable").unwrap_or(true);
276                crate::tools::ctx_pack::handle_auto_load(
277                    name.as_deref(),
278                    version.as_deref(),
279                    enable,
280                )
281            }
282            "summary" => crate::tools::ctx_pack::handle_summary(&project_root),
283            "bundle" => handle_bundle(args, ctx, &project_root)?,
284            _ => "Unknown action. Use: pr, create, list, info, remove, install, export, import, auto_load, summary, bundle".to_string(),
285        };
286
287        Ok(ToolOutput::simple(result))
288    }
289}
290
291/// `action=bundle` (#1885): one budgeted XML document for a chat product.
292/// Returns the XML (or only the report for `emit=plain`); with `file` the XML
293/// is written there and only the report comes back. The secret scan is
294/// always on over MCP.
295fn handle_bundle(
296    args: &Map<String, Value>,
297    ctx: &ToolContext,
298    project_root: &str,
299) -> Result<String, ErrorData> {
300    use crate::core::context_bundle::{self, BundleOptions, Unit, parse_limit};
301    let invalid = |msg: String| ErrorData::invalid_params(msg, None);
302
303    let mut opts = BundleOptions::new(project_root.into());
304    if let Some(path) = ctx.resolved_path("path") {
305        opts.scope = Some(path.into());
306    } else if let Some(err) = ctx.path_error("path") {
307        return Err(invalid(format!("path: {err}")));
308    }
309    match args.get("limit") {
310        Some(Value::String(raw)) => opts.limit = parse_limit(raw).map_err(invalid)?,
311        Some(Value::Number(n)) => {
312            opts.limit = n
313                .as_u64()
314                .and_then(|n| usize::try_from(n).ok())
315                .filter(|n| *n > 0)
316                .ok_or_else(|| invalid("limit must be a positive integer".into()))?;
317        }
318        Some(_) => {
319            return Err(invalid(
320                "limit must be a number or a string like 128k".into(),
321            ));
322        }
323        None => {}
324    }
325    if let Some(unit) = get_str(args, "unit") {
326        opts.unit = Unit::parse(&unit).map_err(invalid)?;
327    }
328    opts.intent = get_str(args, "intent");
329    opts.include = get_str_array(args, "include").unwrap_or_default();
330    opts.exclude = get_str_array(args, "ignore").unwrap_or_default();
331    opts.knowledge = get_str_array(args, "with_knowledge").filter(|c| !c.is_empty());
332    if let Some(n) = get_usize(args, "knowledge_limit") {
333        opts.knowledge_limit = n;
334    }
335    opts.knowledge_auto = get_bool(args, "with_auto").unwrap_or(false);
336
337    let emit = get_str(args, "emit").unwrap_or_else(|| "xml".into());
338    if !matches!(emit.as_str(), "xml" | "plain" | "both") {
339        return Err(invalid(format!(
340            "emit must be xml, plain or both (got '{emit}')"
341        )));
342    }
343    let bundle = context_bundle::build(&opts).map_err(invalid)?;
344    let report = bundle.report();
345
346    if let Some(file) = ctx.resolved_path("file") {
347        if emit == "plain" {
348            return Err(invalid("emit=plain writes no bundle; drop file".into()));
349        }
350        ctx.ensure_writable(file).map_err(invalid)?;
351        std::fs::write(file, &bundle.xml)
352            .map_err(|e| ErrorData::internal_error(format!("cannot write {file}: {e}"), None))?;
353        return Ok(format!("{report}written: {file}"));
354    } else if let Some(err) = ctx.path_error("file") {
355        return Err(invalid(format!("file: {err}")));
356    }
357    Ok(match emit.as_str() {
358        "plain" => report,
359        "both" => format!("{report}\n{}", bundle.xml),
360        _ => bundle.xml,
361    })
362}
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367
368    fn project() -> tempfile::TempDir {
369        let dir = tempfile::tempdir().unwrap();
370        std::fs::write(dir.path().join("main.rs"), "fn main() {}\n").unwrap();
371        dir
372    }
373
374    fn ctx_for(root: &std::path::Path, file: Option<&std::path::Path>) -> ToolContext {
375        let mut ctx = ToolContext {
376            project_root: root.to_string_lossy().into_owned(),
377            ..Default::default()
378        };
379        if let Some(file) = file {
380            ctx.resolved_paths
381                .insert("file".into(), file.to_string_lossy().into_owned());
382        }
383        ctx
384    }
385
386    fn bundle(ctx: &ToolContext, extra: Value) -> Result<String, ErrorData> {
387        let mut args = json!({ "action": "bundle", "limit": "8k" });
388        if let (Some(args), Value::Object(extra)) = (args.as_object_mut(), extra) {
389            args.extend(extra);
390        }
391        CtxPackTool
392            .handle(args.as_object().unwrap(), ctx)
393            .map(|out| out.text)
394    }
395
396    #[test]
397    fn bundle_returns_xml_within_the_limit() {
398        let _iso = crate::core::data_dir::isolated_data_dir();
399        let dir = project();
400        let xml = bundle(&ctx_for(dir.path(), None), json!({})).unwrap();
401        assert!(xml.starts_with("<bundle "), "{xml}");
402        assert!(xml.contains("fn main()"), "{xml}");
403        assert!(xml.chars().count() <= 8000);
404    }
405
406    #[test]
407    fn bundle_rejects_bad_emit_and_limit() {
408        let _iso = crate::core::data_dir::isolated_data_dir();
409        let dir = project();
410        let ctx = ctx_for(dir.path(), None);
411        assert!(bundle(&ctx, json!({ "emit": "html" })).is_err());
412        assert!(bundle(&ctx, json!({ "limit": 0 })).is_err());
413        assert!(bundle(&ctx, json!({ "limit": true })).is_err());
414    }
415
416    #[test]
417    fn bundle_writes_the_file_and_returns_the_report() {
418        let _iso = crate::core::data_dir::isolated_data_dir();
419        let dir = project();
420        let out = dir.path().join("bundle.xml");
421        let report = bundle(&ctx_for(dir.path(), Some(&out)), json!({})).unwrap();
422        assert!(report.contains("written:"), "{report}");
423        let xml = std::fs::read_to_string(&out).unwrap();
424        assert!(xml.starts_with("<bundle "), "{xml}");
425    }
426
427    /// #475: `file` must not write into a read-only root.
428    #[test]
429    fn bundle_refuses_to_write_into_a_read_only_root() {
430        let _iso = crate::core::data_dir::isolated_data_dir();
431        let dir = project();
432        let ro = dir.path().join("refrepo");
433        std::fs::create_dir_all(&ro).unwrap();
434        let out = ro.join("bundle.xml");
435
436        let ro_canon = crate::core::pathjail::canonicalize_or_self(&ro);
437        crate::test_env::set_var(
438            "LEAN_CTX_READ_ONLY_ROOTS",
439            ro_canon.to_string_lossy().as_ref(),
440        );
441        let result = bundle(&ctx_for(dir.path(), Some(&out)), json!({}));
442        crate::test_env::remove_var("LEAN_CTX_READ_ONLY_ROOTS");
443
444        let err = result.expect_err("write into a read-only root must be refused");
445        assert!(err.message.contains("read-only"), "{err:?}");
446        assert!(
447            !out.exists(),
448            "no bundle may be written into a read-only root"
449        );
450    }
451}