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 tool_execution_error,
8};
9use crate::tool_defs::tool_def;
10
11pub struct CtxPackTool;
12
13impl McpTool for CtxPackTool {
14 fn name(&self) -> &'static str {
15 "ctx_pack"
16 }
17
18 fn tool_def(&self) -> Tool {
19 tool_def(
20 "ctx_pack",
21 "WORKFLOW: create -> export -> import -> install for sharing context state.\n\
22 ANTIPATTERN: NOT for ephemeral session save (use ctx_session).\n\
23 Context Package Manager — create, install, manage portable context packages\n\
24 with knowledge, graph, session patterns, and gotchas.\n\
25 Actions: pr, create, list, info, remove, install, export, import, auto_load, summary, bundle.\n\
26 create: select layers/categories/keys/facts; preview:true lists what would be packed, writes nothing.\n\
27 bundle: one budgeted XML document (task-ranked files, signatures, tree) that fits a chat input box.\n\
28 Saves tokens: pre-built context state (avoids re-building).",
29 json!({
30 "type": "object",
31 "properties": {
32 "action": {
33 "type": "string",
34 "enum": ["pr", "create", "list", "info", "remove", "install", "export", "import", "auto_load", "summary", "bundle"],
35 "description": "Pack action to perform"
36 },
37 "path": {
38 "type": "string",
39 "description": "Directory or file to bundle (bundle; default: project root)"
40 },
41 "limit": {
42 "type": "string",
43 "description": "Hard size cap, e.g. 128k, 2M, 32000 (bundle; default 128k)"
44 },
45 "unit": {
46 "type": "string",
47 "enum": ["chars", "tokens"],
48 "description": "What limit counts (bundle; default chars)"
49 },
50 "intent": {
51 "type": "string",
52 "description": "Task the bundle is for; ranks files (bundle; default: session task)"
53 },
54 "emit": {
55 "type": "string",
56 "enum": ["xml", "plain", "both"],
57 "description": "xml bundle, plain allocation report, or both (bundle)"
58 },
59 "include": {
60 "type": "array",
61 "items": { "type": "string" },
62 "description": "Globs to include (bundle)"
63 },
64 "ignore": {
65 "type": "array",
66 "items": { "type": "string" },
67 "description": "Globs to exclude (bundle)"
68 },
69 "with_knowledge": {
70 "type": "array",
71 "items": { "type": "string" },
72 "description": "Knowledge categories to append, e.g. decision, architecture, or all (bundle)"
73 },
74 "knowledge_limit": {
75 "type": "integer",
76 "description": "Max knowledge facts (bundle; default 10)"
77 },
78 "with_auto": {
79 "type": "boolean",
80 "description": "Also include machine-derived auto:* facts (bundle)"
81 },
82 "project_root": {
83 "type": "string",
84 "description": "Project root directory"
85 },
86 "name": {
87 "type": "string",
88 "description": "Package name"
89 },
90 "version": {
91 "type": "string",
92 "description": "Package version (semver)"
93 },
94 "description": {
95 "type": "string",
96 "description": "Package description (for create)"
97 },
98 "author": {
99 "type": "string",
100 "description": "Package author (for create)"
101 },
102 "tags": {
103 "type": "array",
104 "items": { "type": "string" },
105 "description": "Tags for categorization (for create)"
106 },
107 "layers": {
108 "type": "array",
109 "items": { "type": "string" },
110 "description": "Layers to include: knowledge|graph|session|patterns|gotchas"
111 },
112 "categories": {
113 "type": "array",
114 "items": { "type": "string" },
115 "description": "Only facts of these categories (create)"
116 },
117 "keys": {
118 "type": "array",
119 "items": { "type": "string" },
120 "description": "Only facts with these keys (create)"
121 },
122 "facts": {
123 "type": "array",
124 "items": { "type": "string" },
125 "description": "Explicit facts as category/key (create)"
126 },
127 "preview": {
128 "type": "boolean",
129 "description": "Show what create would pack (items, status, sources, validity); writes nothing"
130 },
131 "redistributable": {
132 "type": "boolean",
133 "description": "Grant recipients the right to pass the package on (create)"
134 },
135 "level": {
136 "type": "integer",
137 "description": "Detail level 1-3 (higher = more detail)"
138 },
139 "scope": {
140 "type": "string",
141 "description": "Package scope (e.g. @org/name)"
142 },
143 "base": {
144 "type": "string",
145 "description": "Git base ref for PR diff"
146 },
147 "format": {
148 "type": "string",
149 "enum": ["markdown", "json"],
150 "description": "Output format: markdown|json"
151 },
152 "depth": {
153 "type": "integer",
154 "description": "Impact depth for pr action (default: 3)"
155 },
156 "diff": {
157 "type": "string",
158 "description": "Git diff --name-status text input"
159 },
160 "file": {
161 "type": "string",
162 "description": "File path for import/export; bundle output file"
163 },
164 "apply": {
165 "type": "boolean",
166 "description": "Apply after import (default: false)"
167 },
168 "enable": {
169 "type": "boolean",
170 "description": "Enable auto-load (default: true)"
171 }
172 },
173 "required": ["action"],
174 "allOf": [
175 {
176 "if": { "properties": { "action": { "const": "create" } }, "required": ["action"] },
177 "then": { "required": ["action", "name"] }
178 },
179 {
180 "if": { "properties": { "action": { "const": "info" } }, "required": ["action"] },
181 "then": { "required": ["action", "name"] }
182 },
183 {
184 "if": { "properties": { "action": { "const": "remove" } }, "required": ["action"] },
185 "then": { "required": ["action", "name"] }
186 },
187 {
188 "if": { "properties": { "action": { "const": "install" } }, "required": ["action"] },
189 "then": { "required": ["action", "name"] }
190 },
191 {
192 "if": { "properties": { "action": { "const": "export" } }, "required": ["action"] },
193 "then": { "required": ["action", "name"] }
194 },
195 {
196 "if": { "properties": { "action": { "const": "import" } }, "required": ["action"] },
197 "then": { "required": ["action", "file"] }
198 }
199 ]
200 }),
201 )
202 }
203
204 fn handle(
205 &self,
206 args: &Map<String, Value>,
207 ctx: &ToolContext,
208 ) -> Result<ToolOutput, ErrorData> {
209 let action = get_str(args, "action")
210 .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
211
212 let project_root = if let Some(p) = ctx
213 .resolved_path("project_root")
214 .or(ctx.resolved_path("root"))
215 {
216 p.to_string()
217 } else if let Some(err) = ctx.path_error("project_root").or(ctx.path_error("root")) {
218 return Err(ErrorData::invalid_params(
219 format!("project_root: {err}"),
220 None,
221 ));
222 } else {
223 ctx.project_root.clone()
224 };
225
226 let result = match action.as_str() {
227 "pr" => {
228 let base = get_str(args, "base");
229 let format = get_str(args, "format");
230 let depth = get_usize(args, "depth").map(|d| d.min(64));
231 let diff = get_str(args, "diff");
232 crate::tools::ctx_pack::handle(
233 "pr",
234 &project_root,
235 base.as_deref(),
236 format.as_deref(),
237 depth,
238 diff.as_deref(),
239 )
240 }
241 "create" => {
242 let name = get_str(args, "name")
243 .ok_or_else(|| ErrorData::invalid_params("name is required for create", None))?;
244 use crate::core::context_package::selection::{PackRequest, PackSelection};
245 let request = PackRequest {
246 name,
247 version: get_str(args, "version").unwrap_or_else(|| "1.0.0".into()),
248 description: get_str(args, "description").unwrap_or_default(),
249 author: get_str(args, "author"),
250 tags: get_str_array(args, "tags").unwrap_or_default(),
251 level: get_int(args, "level")
252 .and_then(|l| u32::try_from(l).ok())
253 .unwrap_or(1)
254 .clamp(1, 3),
255 scope: get_str(args, "scope"),
256 private: false,
257 redistributable: get_bool(args, "redistributable").unwrap_or(false),
258 selection: PackSelection {
259 layers: get_str_array(args, "layers").unwrap_or_default(),
260 categories: get_str_array(args, "categories").unwrap_or_default(),
261 keys: get_str_array(args, "keys").unwrap_or_default(),
262 facts: get_str_array(args, "facts").unwrap_or_default(),
263 },
264 };
265 let preview = get_bool(args, "preview").unwrap_or(false);
266 crate::tools::ctx_pack::handle_create(&project_root, &request, preview)
267 }
268 "list" => crate::tools::ctx_pack::handle_list(),
269 "info" => {
270 let name = get_str(args, "name")
271 .ok_or_else(|| ErrorData::invalid_params("name is required for info", None))?;
272 let version = get_str(args, "version");
273 crate::tools::ctx_pack::handle_info(&name, version.as_deref())
274 }
275 "remove" => {
276 let name = get_str(args, "name")
277 .ok_or_else(|| ErrorData::invalid_params("name is required for remove", None))?;
278 let version = get_str(args, "version");
279 crate::tools::ctx_pack::handle_remove(&name, version.as_deref())
280 }
281 "install" => {
282 let name = get_str(args, "name").ok_or_else(|| {
283 ErrorData::invalid_params("name is required for install", None)
284 })?;
285 let version = get_str(args, "version");
286 crate::tools::ctx_pack::handle_install(&name, version.as_deref(), &project_root)
287 }
288 "export" => {
289 let name = get_str(args, "name").ok_or_else(|| {
290 ErrorData::invalid_params("name is required for export", None)
291 })?;
292 let version = get_str(args, "version");
293 let file = get_str(args, "file")
294 .map(|raw| crate::core::workspace_authority::confine(&raw, &project_root, true))
295 .transpose()
296 .map_err(|error| ErrorData::invalid_params(error, None))?;
297 crate::tools::ctx_pack::handle_export(&name, version.as_deref(), file.as_deref())
298 }
299 "import" => {
300 let file = get_str(args, "file")
301 .ok_or_else(|| ErrorData::invalid_params("file is required for import", None))?;
302 let file = crate::core::workspace_authority::confine(&file, &project_root, false)
303 .map_err(|error| ErrorData::invalid_params(error, None))?;
304 let apply = get_bool(args, "apply").unwrap_or(false);
305 crate::tools::ctx_pack::handle_import(&file, apply, &project_root)
306 }
307 "auto_load" => {
308 let name = get_str(args, "name");
309 let version = get_str(args, "version");
310 let enable = get_bool(args, "enable").unwrap_or(true);
311 crate::tools::ctx_pack::handle_auto_load(
312 &project_root,
313 name.as_deref(),
314 version.as_deref(),
315 enable,
316 )
317 }
318 "summary" => crate::tools::ctx_pack::handle_summary(&project_root),
319 "bundle" => handle_bundle(args, ctx, &project_root)?,
320 _ => "Unknown action. Use: pr, create, list, info, remove, install, export, import, auto_load, summary, bundle".to_string(),
321 };
322
323 Ok(ToolOutput::simple(result))
324 }
325}
326
327fn handle_bundle(
332 args: &Map<String, Value>,
333 ctx: &ToolContext,
334 project_root: &str,
335) -> Result<String, ErrorData> {
336 use crate::core::context_bundle::{self, BundleOptions, Unit, parse_limit};
337 let invalid = |msg: String| ErrorData::invalid_params(msg, None);
338
339 let mut opts = BundleOptions::new(project_root.into());
340 if let Some(path) = ctx.resolved_path("path") {
341 opts.scope = Some(path.into());
342 } else if let Some(err) = ctx.path_error("path") {
343 return Err(invalid(format!("path: {err}")));
344 }
345 match args.get("limit") {
346 Some(Value::String(raw)) => opts.limit = parse_limit(raw).map_err(invalid)?,
347 Some(Value::Number(n)) => {
348 opts.limit = n
349 .as_u64()
350 .and_then(|n| usize::try_from(n).ok())
351 .filter(|n| *n > 0)
352 .ok_or_else(|| invalid("limit must be a positive integer".into()))?;
353 }
354 Some(_) => {
355 return Err(invalid(
356 "limit must be a number or a string like 128k".into(),
357 ));
358 }
359 None => {}
360 }
361 if let Some(unit) = get_str(args, "unit") {
362 opts.unit = Unit::parse(&unit).map_err(invalid)?;
363 }
364 opts.intent = get_str(args, "intent");
365 opts.include = get_str_array(args, "include").unwrap_or_default();
366 opts.exclude = get_str_array(args, "ignore").unwrap_or_default();
367 opts.knowledge = get_str_array(args, "with_knowledge").filter(|c| !c.is_empty());
368 if let Some(n) = get_usize(args, "knowledge_limit") {
369 opts.knowledge_limit = n;
370 }
371 opts.knowledge_auto = get_bool(args, "with_auto").unwrap_or(false);
372
373 let emit = get_str(args, "emit").unwrap_or_else(|| "xml".into());
374 if !matches!(emit.as_str(), "xml" | "plain" | "both") {
375 return Err(invalid(format!(
376 "emit must be xml, plain or both (got '{emit}')"
377 )));
378 }
379 let bundle = context_bundle::build(&opts).map_err(tool_execution_error)?;
386 let report = bundle.report();
387 if !bundle.fits() {
388 return Err(tool_execution_error(format!(
389 "{report}bundle is {} {} but the limit is {} — raise limit or narrow path",
390 bundle.size, bundle.unit, bundle.limit
391 )));
392 }
393
394 if let Some(file) = ctx.resolved_path("file") {
395 if emit == "plain" {
396 return Err(invalid("emit=plain writes no bundle; drop file".into()));
397 }
398 let output = context_bundle::export::destination(
401 "ctx_pack",
402 std::path::Path::new(project_root),
403 std::path::Path::new(file),
404 )
405 .map_err(invalid)?;
406 let released = released_bundle(bundle.xml).map_err(tool_execution_error)?;
407 std::fs::write(&output, released)
408 .map_err(|e| tool_execution_error(format!("cannot write {file}: {e}")))?;
409 return Ok(format!("{report}written: {file}"));
410 } else if let Some(err) = ctx.path_error("file") {
411 return Err(invalid(format!("file: {err}")));
412 }
413 Ok(match emit.as_str() {
414 "plain" => report,
415 "both" => format!("{report}\n{}", bundle.xml),
416 _ => bundle.xml,
417 })
418}
419
420fn released_bundle(xml: String) -> Result<String, String> {
425 use rmcp::model::{CallToolResult, ContentBlock};
426 let released = crate::server::policy_guard::release_result(
427 "ctx_pack",
428 CallToolResult::success(vec![ContentBlock::text(xml)]),
429 );
430 let text = released
431 .content
432 .iter()
433 .filter_map(|block| block.as_text().map(|text| text.text.clone()))
434 .collect::<Vec<_>>()
435 .join("\n");
436 if released.is_error == Some(true) {
437 return Err(text);
438 }
439 Ok(crate::server::policy_guard::redact_model_text(&text))
440}
441
442#[cfg(test)]
443mod tests {
444 use super::*;
445
446 fn project() -> tempfile::TempDir {
447 let dir = tempfile::tempdir().unwrap();
448 std::fs::write(dir.path().join("main.rs"), "fn main() {}\n").unwrap();
449 dir
450 }
451
452 fn ctx_for(root: &std::path::Path, file: Option<&std::path::Path>) -> ToolContext {
453 let mut ctx = ToolContext {
454 project_root: root.to_string_lossy().into_owned(),
455 ..Default::default()
456 };
457 if let Some(file) = file {
458 ctx.resolved_paths
459 .insert("file".into(), file.to_string_lossy().into_owned());
460 }
461 ctx
462 }
463
464 fn bundle(ctx: &ToolContext, extra: Value) -> Result<String, ErrorData> {
465 let mut args = json!({ "action": "bundle", "limit": "8k" });
466 if let (Some(args), Value::Object(extra)) = (args.as_object_mut(), extra) {
467 args.extend(extra);
468 }
469 CtxPackTool
470 .handle(args.as_object().unwrap(), ctx)
471 .map(|out| out.text)
472 }
473
474 #[test]
475 fn bundle_returns_xml_within_the_limit() {
476 let _iso = crate::core::data_dir::isolated_data_dir();
477 let dir = project();
478 let xml = bundle(&ctx_for(dir.path(), None), json!({})).unwrap();
479 assert!(xml.starts_with("<bundle "), "{xml}");
480 assert!(xml.contains("fn main()"), "{xml}");
481 assert!(xml.chars().count() <= 8000);
482 }
483
484 #[test]
485 fn bundle_rejects_bad_emit_and_limit() {
486 let _iso = crate::core::data_dir::isolated_data_dir();
487 let dir = project();
488 let ctx = ctx_for(dir.path(), None);
489 assert!(bundle(&ctx, json!({ "emit": "html" })).is_err());
490 assert!(bundle(&ctx, json!({ "limit": 0 })).is_err());
491 assert!(bundle(&ctx, json!({ "limit": true })).is_err());
492 }
493
494 #[test]
495 fn bundle_writes_the_file_and_returns_the_report() {
496 let _iso = crate::core::data_dir::isolated_data_dir();
497 let dir = project();
498 let out = dir.path().join("bundle.xml");
499 let report = bundle(&ctx_for(dir.path(), Some(&out)), json!({})).unwrap();
500 assert!(report.contains("written:"), "{report}");
501 let xml = std::fs::read_to_string(&out).unwrap();
502 assert!(xml.starts_with("<bundle "), "{xml}");
503 }
504
505 #[test]
507 fn bundle_refuses_to_write_into_a_read_only_root() {
508 let _iso = crate::core::data_dir::isolated_data_dir();
509 let dir = project();
510 let ro = dir.path().join("refrepo");
511 std::fs::create_dir_all(&ro).unwrap();
512 let out = ro.join("bundle.xml");
513
514 let ro_canon = crate::core::pathjail::canonicalize_or_self(&ro);
515 crate::test_env::set_var(
516 "LEAN_CTX_READ_ONLY_ROOTS",
517 ro_canon.to_string_lossy().as_ref(),
518 );
519 let result = bundle(&ctx_for(dir.path(), Some(&out)), json!({}));
520 crate::test_env::remove_var("LEAN_CTX_READ_ONLY_ROOTS");
521
522 let err = result.expect_err("write into a read-only root must be refused");
523 assert!(err.message.contains("read-only"), "{err:?}");
524 assert!(
525 !out.exists(),
526 "no bundle may be written into a read-only root"
527 );
528 }
529
530 #[test]
535 fn create_packs_the_selection_and_preview_shows_it_without_writing() {
536 use crate::core::context_package::LocalRegistry;
537 use crate::core::knowledge::{FactStatus, ProjectKnowledge};
538 let _iso = crate::core::data_dir::isolated_data_dir();
539 let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
540 let dir = project();
541 let root = dir.path().to_string_lossy().into_owned();
542 ProjectKnowledge::mutate_locked(&root, |k| {
543 let policy = crate::core::memory_policy::MemoryPolicy::default();
544 for (category, key, value) in [
545 ("architecture", "db", "orders live in postgres 16"),
546 ("architecture", "cache", "sessions are cached in redis"),
547 ("architecture", "queue", "jobs run on a vendor queue"),
548 ("decision", "style", "the parser is hand-written"),
549 ] {
550 k.remember(category, key, value, "fixture", 0.9, &policy);
551 let fact = k.facts.last_mut().unwrap();
552 match key {
553 "db" => fact.status = Some(FactStatus::Verified),
554 "queue" => fact.imported_from = Some("vendor-notes@1.0.0".into()),
555 _ => {}
556 }
557 }
558 })
559 .unwrap();
560 let ctx = ctx_for(dir.path(), None);
561 let create = |preview: bool| {
562 let args = json!({
563 "action": "create", "name": "selected", "layers": ["knowledge"],
564 "categories": ["architecture"], "preview": preview,
565 });
566 CtxPackTool
567 .handle(args.as_object().unwrap(), &ctx)
568 .unwrap()
569 .text
570 };
571
572 let preview = create(true);
573 assert!(
574 LocalRegistry::open().unwrap().list().unwrap().is_empty(),
575 "a preview writes nothing: {preview}"
576 );
577 assert!(
578 preview.contains("Knowledge facts: 2 (1 verified, 1 assumption)"),
579 "{preview}"
580 );
581 assert!(preview.contains("[verified] architecture/db: orders live in postgres 16"));
582 assert!(
583 preview.contains("[assumption] architecture/cache"),
584 "{preview}"
585 );
586 assert!(preview.contains("Not selected: 1 fact(s)"), "{preview}");
587 assert!(
588 preview.contains("Withheld: architecture/queue — merged from vendor-notes@1.0.0"),
589 "{preview}"
590 );
591 assert!(!preview.contains("decision/style"), "{preview}");
592
593 let created = create(false);
594 let (_, content) = LocalRegistry::open()
595 .unwrap()
596 .load_package("selected", "1.0.0")
597 .unwrap_or_else(|e| panic!("{e}: {created}"));
598 let packed: Vec<_> = content
599 .knowledge
600 .unwrap()
601 .facts
602 .into_iter()
603 .map(|f| (format!("{}/{}", f.category, f.key), f.status))
604 .collect();
605 assert_eq!(
606 packed,
607 [
608 ("architecture/db".into(), Some(FactStatus::Verified)),
609 ("architecture/cache".into(), Some(FactStatus::Assumption)),
610 ]
611 );
612 for (fact, status) in &packed {
613 let line = format!("[{}] {fact}:", status.unwrap().as_str());
614 assert!(preview.contains(&line), "preview lacks {line}: {preview}");
615 }
616 }
617}