Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

M13: `pdfcraft-cli mcp --compact` lists 12 tools and finds the rest by search (#353)

Oldrich333868bd727d19c
diff --git a/README.md b/README.md
index e08d55512..a80469bcd 100644
--- a/README.md
+++ b/README.md
@@ -291,6 +291,8 @@ Every engine feature is reachable without the GUI, through one table of JSON-Sch
{ "mcpServers": { "pdfcraft": { "command": "pdfcraft-cli", "args": ["mcp", "--root", "/path/to/your/pdfs"] } } }
```
+ `--compact` shrinks the tool list the agent has to read: `tools/list` returns about ten core tools plus `tool_search` and `tool_call`, which find and run every other tool, so the list costs far fewer tokens. Every tool still works.
+
`--root` confines every file the agent can read or write to one directory. Builds that should not include the server at all can use `cargo build -p pdfcraft-cli --no-default-features`.
- **The Rust API** (`pdfcraft_automation::Automation::call`), for embedding.
diff --git a/apps/pdfcraft-cli/src/main.rs b/apps/pdfcraft-cli/src/main.rs
index 011d8320b..3c05c0c4b 100644
--- a/apps/pdfcraft-cli/src/main.rs
+++ b/apps/pdfcraft-cli/src/main.rs
@@ -13,7 +13,8 @@
//! pdfcraft-cli tools automation tools and their JSON Schemas
//! pdfcraft-cli run <tool> [key=value …] [--root DIR] [--out image.png]
//! pdfcraft-cli run --script steps.json [--root DIR] [{"tool": "doc_open", "args": {…}}, …]
-//! pdfcraft-cli mcp [--root DIR] MCP server on stdin/stdout (opt-in)
+//! pdfcraft-cli mcp [--root DIR] [--compact] MCP server on stdin/stdout (opt-in)
+//! --compact lists a core set of tools plus tool_search and tool_call
//! pdfcraft-cli ui --control FILE <method> [key=value …] [--out shot.png]
//! drive a running app started with --control FILE
//! ```
@@ -579,8 +580,13 @@ fn run(args: &[String]) -> Result<(), CliError> {
#[cfg(feature = "mcp")]
fn mcp(args: &[String]) -> Result<(), CliError> {
- let mut server = pdfcraft_automation::mcp::McpServer::new(automation(args)?);
- eprintln!("pdfcraft-cli: MCP server on stdio (protocol {}); close stdin to stop", pdfcraft_automation::mcp::PROTOCOL_VERSIONS[0]);
+ let compact = args.iter().any(|a| a == "--compact");
+ let mut server = pdfcraft_automation::mcp::McpServer::new(automation(args)?).with_compact(compact);
+ eprintln!(
+ "pdfcraft-cli: MCP server on stdio (protocol {}{}); close stdin to stop",
+ pdfcraft_automation::mcp::PROTOCOL_VERSIONS[0],
+ if compact { ", compact tool list" } else { "" }
+ );
server.serve(std::io::stdin().lock(), std::io::stdout().lock()).map_err(|e| CliError::Message(e.to_string()))
}
diff --git a/apps/pdfcraft-cli/tests/mcp_compact.rs b/apps/pdfcraft-cli/tests/mcp_compact.rs
new file mode 100644
index 000000000..8c12152a3
--- /dev/null
+++ b/apps/pdfcraft-cli/tests/mcp_compact.rs
@@ -0,0 +1,76 @@
+//! `pdfcraft-cli mcp --compact`: the flag reaches the server, `--root` is still honoured, and plain `mcp` still lists every tool.
+#![cfg(feature = "mcp")]
+
+use std::io::Write as _;
+use std::process::{Command, Stdio};
+
+use serde_json::{Value, json};
+
+/// Run `pdfcraft-cli mcp <flags>` over an initialize request plus `requests` and return the replies to `requests`.
+fn session(flags: &[&str], requests: &[Value]) -> Vec<Value> {
+ let mut child = Command::new(env!("CARGO_BIN_EXE_pdfcraft-cli"))
+ .arg("mcp")
+ .args(flags)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .spawn()
+ .unwrap();
+ let mut input = String::from("{\"jsonrpc\":\"2.0\",\"id\":0,\"method\":\"initialize\",\"params\":{}}\n");
+ for r in requests {
+ input.push_str(&r.to_string());
+ input.push('\n');
+ }
+ child.stdin.take().unwrap().write_all(input.as_bytes()).unwrap();
+ let out = child.wait_with_output().unwrap();
+ assert!(out.status.success());
+ String::from_utf8(out.stdout).unwrap().lines().skip(1).map(|l| serde_json::from_str(l).unwrap()).collect()
+}
+
+fn request(id: u64, method: &str, params: Value) -> Value {
+ json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params })
+}
+
+/// The `tools/list` tool names of `pdfcraft-cli mcp <flags>`.
+fn listed_tools(flags: &[&str]) -> Vec<String> {
+ let reply = session(flags, &[request(1, "tools/list", json!({}))]).remove(0);
+ reply["result"]["tools"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap().to_string()).collect()
+}
+
+#[test]
+fn compact_flag_shortens_the_tool_list() {
+ let full = listed_tools(&[]);
+ let compact = listed_tools(&["--compact"]);
+ assert_eq!(compact.len(), 12, "{compact:?}");
+ assert!(compact.iter().any(|n| n == "tool_search") && compact.iter().any(|n| n == "tool_call"));
+ assert!(compact.iter().all(|n| full.contains(n) || n == "tool_search" || n == "tool_call"));
+ assert!(full.len() > 100 && !full.iter().any(|n| n == "tool_search"), "{} tools", full.len());
+ // The flag can sit on either side of --root.
+ assert_eq!(listed_tools(&["--root", ".", "--compact"]), compact);
+ assert_eq!(listed_tools(&["--compact", "--root", "."]), compact);
+}
+
+#[test]
+fn compact_flag_keeps_the_root() {
+ let root = std::env::temp_dir().join(format!("pdfcraft-cli-compact-root-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&root);
+ std::fs::create_dir_all(&root).unwrap();
+ let outside = std::env::temp_dir().join(format!("pdfcraft-cli-compact-outside-{}.pdf", std::process::id()));
+ let outside = outside.to_string_lossy().into_owned();
+ let root_arg = root.to_string_lossy().into_owned();
+ let open_outside =
+ request(1, "tools/call", json!({ "name": "tool_call", "arguments": { "name": "doc_open", "arguments": { "path": outside } } }));
+ let text = |reply: &Value| reply["result"]["content"][0]["text"].as_str().unwrap_or_default().to_string();
+
+ // With the root, in either flag order, a path outside it is refused with the root's own message.
+ for flags in [vec!["--root", root_arg.as_str(), "--compact"], vec!["--compact", "--root", root_arg.as_str()]] {
+ let reply = session(&flags, std::slice::from_ref(&open_outside)).remove(0);
+ assert_eq!(reply["result"]["isError"], true, "{flags:?}: {reply}");
+ assert!(text(&reply).contains("is outside the allowed directory"), "{flags:?}: {}", text(&reply));
+ }
+ // Without a root the same call gets past that check (the file does not exist, so it fails for that reason instead).
+ let reply = session(&["--compact"], std::slice::from_ref(&open_outside)).remove(0);
+ assert_eq!(reply["result"]["isError"], true, "{reply}");
+ assert!(!text(&reply).contains("is outside the allowed directory"), "{}", text(&reply));
+ let _ = std::fs::remove_dir_all(&root);
+}
diff --git a/crates/automation/README.md b/crates/automation/README.md
index d1d60f076..5bc4ac112 100644
--- a/crates/automation/README.md
+++ b/crates/automation/README.md
@@ -30,6 +30,8 @@ mcp::McpServer::new(a).serve(stdin, stdout)? // newline-delimited JS
**Opt-in only.** Nothing starts it automatically, and it opens no port. It runs while `pdfcraft-cli mcp [--root DIR]` runs, normally launched by an agent from its MCP configuration. It stops when stdin closes. The CLI's `mcp` Cargo feature (on by default) compiles it out entirely when disabled.
+`pdfcraft-cli mcp --compact` (or `McpServer::with_compact(true)`) keeps `tools/list` short for agents with small context budgets. It lists only the core tools (`mcp::COMPACT_CORE_TOOLS`: open, info, save, close, render, text extract and find, combine, split, undo) plus two meta tools: `tool_search` (optional `query` and `category`, the name prefix; or `name` for one tool's full `input_schema`) and `tool_call` (`name` and `arguments`, run through the same `Automation::call`). `tools/call` by name keeps working for every tool, and the server instructions mention the meta tools. Without the flag nothing changes.
+
Implemented: `initialize` (protocol 2025-06-18, 2025-03-26, 2024-11-05), `ping`, `tools/list` (with `readOnlyHint`/`destructiveHint` annotations), `tools/call` (JSON results also returned as `structuredContent`; images as `image/png`), and `resources/list`, `resources/templates/list` and `resources/read`. The resources expose the open documents read-only: `pdfcraft://doc/{doc}/info` (JSON), `…/text`, `…/page/{page}/text` and `…/page/{page}/image{?dpi}` (PNG, 1–600 dpi). Tool failures come back as `isError: true` results, so the agent can read and recover from them.
## Adding a tool
diff --git a/crates/automation/src/mcp.rs b/crates/automation/src/mcp.rs
index e746cf534..145190937 100644
--- a/crates/automation/src/mcp.rs
+++ b/crates/automation/src/mcp.rs
@@ -31,13 +31,34 @@ const INSTRUCTIONS: &str = "PdfCraft edits PDFs. Open a file with doc_open to ge
(edit_undo) and stay in memory until doc_save. Page numbers are 1-based. Open documents are also \
resources: pdfcraft://doc/{doc}/info, /text, /page/{page}/text and /page/{page}/image.";
+/// Appended to the instructions in compact mode.
+const COMPACT_INSTRUCTIONS: &str = " Only a core set of tools is listed. Every other tool is still available: find it with \
+tool_search (optional query and category, or name for its full input schema) and run it with tool_call.";
+
+/// The tools `tools/list` returns in compact mode, besides the two meta tools.
+pub const COMPACT_CORE_TOOLS: &[&str] =
+ &["doc_open", "doc_info", "doc_save", "doc_close", "page_render", "text_extract", "text_find", "doc_combine", "doc_split", "edit_undo"];
+
+/// Meta tools that exist only in compact mode.
+const TOOL_SEARCH: &str = "tool_search";
+const TOOL_CALL: &str = "tool_call";
+
pub struct McpServer {
automation: Automation,
+ compact: bool,
}
impl McpServer {
pub fn new(automation: Automation) -> Self {
- Self { automation }
+ Self { automation, compact: false }
+ }
+
+ /// In compact mode `tools/list` returns only [`COMPACT_CORE_TOOLS`] plus `tool_search` and
+ /// `tool_call`, which find and run any other tool. `tools/call` accepts every tool by name
+ /// either way. Off by default.
+ pub fn with_compact(mut self, on: bool) -> Self {
+ self.compact = on;
+ self
}
pub fn automation(&self) -> &Automation {
@@ -93,18 +114,35 @@ impl McpServer {
"protocolVersion": version,
"capabilities": { "tools": { "listChanged": false }, "resources": { "listChanged": false, "subscribe": false } },
"serverInfo": { "name": "pdfcraft", "title": "PdfCraft", "version": env!("CARGO_PKG_VERSION"), "websiteUrl": pdfcraft_engine::links::APP_PAGE },
- "instructions": INSTRUCTIONS,
+ "instructions": if self.compact { format!("{INSTRUCTIONS}{COMPACT_INSTRUCTIONS}") } else { INSTRUCTIONS.to_string() },
}))
}
"ping" => Ok(json!({})),
- "tools/list" => Ok(json!({ "tools": crate::tools().iter().map(tool_json).collect::<Vec<_>>() })),
+ "tools/list" => Ok(json!({ "tools": self.tool_list() })),
"tools/call" => {
let name = params.get("name").and_then(Value::as_str).ok_or((INVALID_PARAMS, "tools/call needs a tool name".to_string()))?;
let args = params.get("arguments").cloned().unwrap_or(Value::Null);
+ if self.compact && name == TOOL_SEARCH {
+ return Ok(match search_tools(&args) {
+ Ok(found) => call_result(vec![Content::Json(found)]),
+ Err(message) => tool_error(&message),
+ });
+ }
+ if self.compact && name == TOOL_CALL {
+ let (inner, inner_args) = match unwrap_tool_call(&args) {
+ Ok(pair) => pair,
+ Err(message) => return Ok(tool_error(&message)),
+ };
+ return Ok(match self.automation.call(&inner, &inner_args) {
+ Ok(content) => call_result(content),
+ Err(ToolError::UnknownTool(t)) => tool_error(&format!("unknown tool {t:?}; use tool_search to find the right name")),
+ Err(e) => tool_error(&e.to_string()),
+ });
+ }
match self.automation.call(name, &args) {
Ok(content) => Ok(call_result(content)),
Err(ToolError::UnknownTool(t)) => Err((INVALID_PARAMS, format!("unknown tool {t:?}"))),
- Err(e) => Ok(json!({ "content": [{ "type": "text", "text": e.to_string() }], "isError": true })),
+ Err(e) => Ok(tool_error(&e.to_string())),
}
}
"resources/list" => Ok(json!({ "resources": self.resource_list() })),
@@ -118,6 +156,149 @@ impl McpServer {
}
}
+impl McpServer {
+ /// What `tools/list` returns: every tool, or in compact mode the core set and the meta tools.
+ fn tool_list(&self) -> Vec<Value> {
+ let all = crate::tools();
+ if !self.compact {
+ return all.iter().map(tool_json).collect();
+ }
+ let mut out: Vec<Value> = COMPACT_CORE_TOOLS.iter().filter_map(|n| all.iter().find(|t| t.name == *n)).map(tool_json).collect();
+ out.extend(meta_tools());
+ out
+ }
+}
+
+/// The two tools only compact mode lists.
+fn meta_tools() -> [Value; 2] {
+ [
+ json!({
+ "name": TOOL_SEARCH,
+ "title": "Find PdfCraft tools",
+ "description": "Search and list all PdfCraft automation tools, including the core tools, with a one-sentence description each. Filter by query \
+ (words matched against name, title and description) and/or category (the name prefix: doc, page, text, form, …). \
+ With name, return that one tool in full, including its input_schema. Run a tool with tool_call.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "query": { "type": "string", "description": "Words to look for, all of which must match (case-insensitive)." },
+ "category": { "type": "string", "description": "Tool name prefix, e.g. page, text, form, redact." },
+ "name": { "type": "string", "description": "Exact tool name: return its description and input_schema." },
+ },
+ "required": [],
+ "additionalProperties": false,
+ },
+ "annotations": { "title": "Find PdfCraft tools", "readOnlyHint": true, "destructiveHint": false, "openWorldHint": false },
+ }),
+ json!({
+ "name": TOOL_CALL,
+ "title": "Run any PdfCraft tool",
+ "description": "Run any PdfCraft tool by name with its arguments, exactly as if it were called directly. \
+ Find names and argument schemas with tool_search. The result is the tool's own result.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "name": { "type": "string", "description": "The tool to run, e.g. page_rotate." },
+ "arguments": { "type": "object", "description": "The tool's arguments (see its input_schema from tool_search)." },
+ },
+ "required": ["name"],
+ "additionalProperties": false,
+ },
+ "annotations": { "title": "Run any PdfCraft tool", "readOnlyHint": false, "destructiveHint": true, "openWorldHint": false },
+ }),
+ ]
+}
+
+/// The category of a tool: its name up to the first underscore (`page_rotate` → `page`).
+fn category_of(name: &str) -> &str {
+ name.split('_').next().unwrap_or(name)
+}
+
+/// A description up to and including its first sentence.
+fn first_sentence(text: &str) -> &str {
+ // ASCII lowercasing keeps byte offsets, so positions found in `lower` are valid in `text`.
+ let lower = text.to_ascii_lowercase();
+ let mut from = 0;
+ while let Some(i) = lower.get(from..).and_then(|rest| rest.find(". ")).map(|i| i + from) {
+ // "e.g. " and "i.e. " are abbreviations, not the end of the sentence.
+ if !lower.get(..i).is_some_and(|before| before.ends_with("e.g") || before.ends_with("i.e")) {
+ return text.get(..=i).unwrap_or(text);
+ }
+ from = i + 2;
+ }
+ text
+}
+
+/// Reject keys other than `allowed`, as the tool table does for a tool's own arguments.
+fn check_keys(tool: &str, args: &Value, allowed: &[&str]) -> Result<(), String> {
+ match args.as_object().and_then(|o| o.keys().find(|k| !allowed.contains(&k.as_str()))) {
+ Some(k) => Err(format!("{tool}: unknown argument {k:?} (expected: {})", allowed.join(", "))),
+ None => Ok(()),
+ }
+}
+
+/// `tool_search`: filter the tool table by query and category, or describe one tool in full.
+fn search_tools(args: &Value) -> Result<Value, String> {
+ if !(args.is_object() || args.is_null()) {
+ return Err(format!("{TOOL_SEARCH} takes an object with optional query, category and name"));
+ }
+ check_keys(TOOL_SEARCH, args, &["query", "category", "name"])?;
+ let text = |key: &str| match args.get(key) {
+ None | Some(Value::Null) => Ok(None),
+ Some(Value::String(s)) => Ok(Some(s.trim())),
+ Some(_) => Err(format!("{TOOL_SEARCH}: {key} must be a string")),
+ };
+ let (query, category, name) = (text("query")?, text("category")?, text("name")?);
+ let all = crate::tools();
+ if let Some(name) = name {
+ let t =
+ all.iter().find(|t| t.name == name).ok_or_else(|| format!("unknown tool {name:?}; call {TOOL_SEARCH} without name to list the tools"))?;
+ return Ok(json!({ "tool": {
+ "name": t.name, "title": t.title, "category": category_of(t.name), "description": t.description,
+ "read_only": t.read_only, "destructive": t.destructive, "input_schema": t.input_schema,
+ } }));
+ }
+ let category = category.map(|c| c.trim_end_matches('_').to_lowercase()).filter(|c| !c.is_empty());
+ let words: Vec<String> = query.map(|q| q.to_lowercase().split_whitespace().map(str::to_owned).collect()).unwrap_or_default();
+ let mut categories: Vec<&str> = all.iter().map(|t| category_of(t.name)).collect();
+ categories.sort_unstable();
+ categories.dedup();
+ let found: Vec<Value> = all
+ .iter()
+ .filter(|t| category.as_deref().is_none_or(|c| category_of(t.name) == c))
+ .filter(|t| {
+ let haystack = format!("{} {} {}", t.name, t.title, t.description).to_lowercase();
+ words.iter().all(|w| haystack.contains(w.as_str()))
+ })
+ .map(|t| json!({ "name": t.name, "category": category_of(t.name), "description": first_sentence(t.description), "read_only": t.read_only }))
+ .collect();
+ Ok(json!({ "count": found.len(), "tools": found, "categories": categories }))
+}
+
+/// `tool_call`: the tool name and its arguments from the meta tool's own arguments.
+fn unwrap_tool_call(args: &Value) -> Result<(String, Value), String> {
+ let Some(obj) = args.as_object() else { return Err(format!("{TOOL_CALL} needs an object with name and arguments")) };
+ check_keys(TOOL_CALL, args, &["name", "arguments"])?;
+ let name = obj
+ .get("name")
+ .and_then(Value::as_str)
+ .ok_or_else(|| format!("{TOOL_CALL} needs the name of the tool to run; find it with {TOOL_SEARCH}"))?;
+ if name == TOOL_CALL || name == TOOL_SEARCH {
+ return Err(format!("{TOOL_SEARCH} and {TOOL_CALL} are called directly, not through {TOOL_CALL}"));
+ }
+ let inner = match obj.get("arguments") {
+ None | Some(Value::Null) => Value::Null,
+ Some(v @ Value::Object(_)) => v.clone(),
+ Some(_) => return Err(format!("{TOOL_CALL}: arguments must be an object")),
+ };
+ Ok((name.to_owned(), inner))
+}
+
+/// A failed tool call, as the agent should read it.
+fn tool_error(message: &str) -> Value {
+ json!({ "content": [{ "type": "text", "text": message }], "isError": true })
+}
+
/// The resource behind a `pdfcraft://` URI.
#[derive(Debug, PartialEq)]
enum Resource {
@@ -262,7 +443,19 @@ fn call_result(content: Vec<Content>) -> Value {
#[cfg(test)]
mod tests {
- use super::{Resource, parse_uri};
+ use super::{Resource, first_sentence, parse_uri};
+
+ #[test]
+ fn first_sentence_skips_abbreviations() {
+ assert_eq!(first_sentence("Rotate pages. Undoable."), "Rotate pages.");
+ assert_eq!(first_sentence("Label pages (i.e. roman numerals). Undoable."), "Label pages (i.e. roman numerals).");
+ assert_eq!(first_sentence("Label pages (I.E. roman numerals, E.G. i, ii). Undoable."), "Label pages (I.E. roman numerals, E.G. i, ii).");
+ assert_eq!(first_sentence("Use a value, e.g. en-US, or none. Then more."), "Use a value, e.g. en-US, or none.");
+ assert_eq!(first_sentence("No full stop here"), "No full stop here");
+ assert_eq!(first_sentence("Only an abbreviation, e.g. this"), "Only an abbreviation, e.g. this");
+ assert_eq!(first_sentence(""), "");
+ assert_eq!(first_sentence("Zażółć gęślą, i.e. jaźń. Dalej."), "Zażółć gęślą, i.e. jaźń.");
+ }
#[test]
fn resource_uris_parse() {
diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rs
index 2f4449a9d..95407fd4f 100644
--- a/crates/automation/tests/automation.rs
+++ b/crates/automation/tests/automation.rs
@@ -590,6 +590,272 @@ fn mcp_resources_expose_open_documents() {
assert_eq!(rpc(&mut s, 7, "resources/read", json!({ "uri": "pdfcraft://doc/1/page/9/image" }))["error"]["code"], -32602);
}
+/// A server in compact mode with `dir` as its root.
+#[cfg(feature = "mcp")]
+fn compact_server(dir: &Path) -> McpServer {
+ McpServer::new(auto(dir)).with_compact(true)
+}
+
+/// Run a tool through the compact server's `tool_call`.
+#[cfg(feature = "mcp")]
+fn via_tool_call(s: &mut McpServer, id: u64, tool: &str, arguments: Value) -> Value {
+ rpc(s, id, "tools/call", json!({ "name": "tool_call", "arguments": { "name": tool, "arguments": arguments } }))
+}
+
+#[cfg(feature = "mcp")]
+fn tool_names(reply: &Value) -> Vec<String> {
+ reply["result"]["tools"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap().to_string()).collect()
+}
+
+#[cfg(feature = "mcp")]
+#[test]
+fn mcp_default_lists_every_tool_and_has_no_meta_tools() {
+ let mut s = McpServer::new(Automation::new());
+ let names = tool_names(&rpc(&mut s, 1, "tools/list", json!({})));
+ assert_eq!(names.len(), tools().len());
+ assert!(!names.iter().any(|n| n == "tool_search" || n == "tool_call"));
+ assert!(!rpc(&mut s, 2, "initialize", json!({}))["result"]["instructions"].as_str().unwrap().contains("tool_search"));
+ // Without --compact the meta tools do not exist.
+ assert_eq!(rpc(&mut s, 3, "tools/call", json!({ "name": "tool_search" }))["error"]["code"], -32602);
+}
+
+#[cfg(feature = "mcp")]
+#[test]
+fn mcp_compact_lists_the_core_tools_and_two_meta_tools() {
+ let mut s = McpServer::new(Automation::new()).with_compact(true);
+ let list = rpc(&mut s, 1, "tools/list", json!({}));
+ let mut expected: Vec<String> = pdfcraft_automation::mcp::COMPACT_CORE_TOOLS.iter().map(|n| n.to_string()).collect();
+ expected.extend(["tool_search".to_string(), "tool_call".to_string()]);
+ assert_eq!(tool_names(&list), expected);
+ let all: Vec<&str> = tools().iter().map(|t| t.name).collect();
+ for core in pdfcraft_automation::mcp::COMPACT_CORE_TOOLS {
+ assert!(all.contains(core), "core tool {core} is not in the tool table");
+ }
+ // Core tools are the real definitions, and the list is far smaller than the full one.
+ let full = rpc(&mut McpServer::new(Automation::new()), 2, "tools/list", json!({}));
+ let core_open = list["result"]["tools"][0].clone();
+ assert_eq!(Some(&core_open), full["result"]["tools"].as_array().unwrap().iter().find(|t| t["name"] == "doc_open"));
+ assert!(list.to_string().len() * 5 < full.to_string().len(), "compact {} vs full {}", list.to_string().len(), full.to_string().len());
+ for meta in &list["result"]["tools"].as_array().unwrap()[10..] {
+ assert_eq!(meta["inputSchema"]["type"], "object");
+ }
+ let instructions = rpc(&mut s, 3, "initialize", json!({}))["result"]["instructions"].as_str().unwrap().to_string();
+ assert!(instructions.contains("tool_search") && instructions.contains("tool_call"), "{instructions}");
+}
+
+#[cfg(feature = "mcp")]
+#[test]
+fn mcp_compact_tool_search_filters_by_query_and_category() {
+ let mut s = McpServer::new(Automation::new()).with_compact(true);
+ let mut search = |args: Value| rpc(&mut s, 1, "tools/call", json!({ "name": "tool_search", "arguments": args }));
+
+ let everything = search(json!({}));
+ assert_eq!(everything["result"]["isError"], false);
+ assert_eq!(everything["result"]["structuredContent"]["count"], tools().len());
+ let first = &everything["result"]["structuredContent"]["tools"][0];
+ assert!(first["name"].is_string() && first["description"].is_string() && first["read_only"].is_boolean(), "{first}");
+
+ let rotate = search(json!({ "query": "ROTATE" }))["result"]["structuredContent"].clone();
+ let names: Vec<&str> = rotate["tools"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap()).collect();
+ assert!(names.contains(&"page_rotate"), "{names:?}");
+ assert!(names.len() < tools().len());
+
+ let docs = search(json!({ "category": "doc" }))["result"]["structuredContent"].clone();
+ let expected = tools().iter().filter(|t| t.name.starts_with("doc_")).count();
+ assert!(expected > 0);
+ assert_eq!(docs["count"], expected);
+ assert!(docs["tools"].as_array().unwrap().iter().all(|t| t["name"].as_str().unwrap().starts_with("doc_") && t["category"] == "doc"));
+
+ let both = search(json!({ "category": "page", "query": "rotate" }))["result"]["structuredContent"].clone();
+ assert!(both["tools"].as_array().unwrap().iter().all(|t| t["name"].as_str().unwrap().starts_with("page_")));
+ assert!(both["tools"].as_array().unwrap().iter().any(|t| t["name"] == "page_rotate"));
+
+ // No match is an empty result that lists the categories, not an error.
+ let none = search(json!({ "category": "nonsense" }));
+ assert_eq!(none["result"]["isError"], false);
+ assert_eq!(none["result"]["structuredContent"]["count"], 0);
+ assert!(none["result"]["structuredContent"]["categories"].as_array().unwrap().iter().any(|c| c == "page"));
+
+ // One tool in full.
+ let one = search(json!({ "name": "page_rotate" }))["result"]["structuredContent"]["tool"].clone();
+ assert_eq!(one["name"], "page_rotate");
+ assert_eq!(one["input_schema"]["type"], "object");
+ let def = tools().into_iter().find(|t| t.name == "page_rotate").unwrap();
+ assert_eq!(one["input_schema"], def.input_schema);
+ assert_eq!(one["description"], def.description);
+
+ // Bad arguments are tool errors.
+ for bad in [json!({ "name": "no_such_tool" }), json!({ "query": 3 }), json!({ "category": ["doc"] }), json!("doc")] {
+ let r = search(bad.clone());
+ assert_eq!(r["result"]["isError"], true, "{bad}");
+ assert!(r["result"]["content"][0]["text"].as_str().is_some_and(|t| !t.is_empty()));
+ }
+}
+
+#[cfg(feature = "mcp")]
+#[test]
+fn mcp_compact_tool_call_dispatches_to_any_tool() {
+ let dir = workdir("mcp-compact");
+ let mut s = compact_server(&dir);
+ let opened = via_tool_call(&mut s, 1, "doc_open", json!({ "path": "a.pdf" }));
+ assert_eq!(opened["result"]["isError"], false);
+ assert_eq!(opened["result"]["structuredContent"]["pages"], 3);
+
+ // A tool outside the core list, through the meta tool.
+ let deleted = via_tool_call(&mut s, 2, "page_delete", json!({ "doc": 1, "pages": [3] }));
+ assert_eq!(deleted["result"]["isError"], false, "{deleted}");
+ assert_eq!(deleted["result"]["structuredContent"]["pages"], 2);
+
+ // The same tool called by name directly still works, and sees the same session.
+ let listed = rpc(&mut s, 3, "tools/call", json!({ "name": "doc_list", "arguments": {} }));
+ assert_eq!(listed["result"]["isError"], false);
+ assert_eq!(listed["result"]["structuredContent"]["documents"][0]["pages"], 2);
+
+ // Images come back as images.
+ let png = via_tool_call(&mut s, 4, "page_render", json!({ "doc": 1, "page": 1, "dpi": 36 }));
+ assert_eq!(png["result"]["content"][0]["type"], "image");
+
+ // `arguments` may be left out for tools that need none.
+ assert_eq!(via_tool_call(&mut s, 5, "doc_list", Value::Null)["result"]["isError"], false);
+ let no_args = rpc(&mut s, 6, "tools/call", json!({ "name": "tool_call", "arguments": { "name": "doc_list" } }));
+ assert_eq!(no_args["result"]["isError"], false);
+
+ // The result equals what the direct call returns.
+ let direct = rpc(&mut s, 7, "tools/call", json!({ "name": "doc_info", "arguments": { "doc": 1 } }));
+ let wrapped = via_tool_call(&mut s, 8, "doc_info", json!({ "doc": 1 }));
+ assert_eq!(direct["result"], wrapped["result"]);
+}
+
+#[cfg(feature = "mcp")]
+#[test]
+fn mcp_compact_tool_call_reports_errors_without_panicking() {
+ let dir = workdir("mcp-compact-errors");
+ let mut s = compact_server(&dir);
+ let text = |r: &Value| r["result"]["content"][0]["text"].as_str().unwrap_or_default().to_string();
+
+ let unknown = via_tool_call(&mut s, 1, "no_such_tool", json!({}));
+ assert_eq!(unknown["result"]["isError"], true);
+ assert!(text(&unknown).contains("no_such_tool") && text(&unknown).contains("tool_search"), "{}", text(&unknown));
+
+ // The tool's own validation errors pass through.
+ let missing = via_tool_call(&mut s, 2, "doc_open", json!({}));
+ assert_eq!(missing["result"]["isError"], true);
+ let outside = via_tool_call(&mut s, 3, "doc_open", json!({ "path": "/definitely/not/here.pdf" }));
+ assert_eq!(outside["result"]["isError"], true);
+ let wrong_type = via_tool_call(&mut s, 4, "page_delete", json!({ "doc": "one", "pages": "all" }));
+ assert_eq!(wrong_type["result"]["isError"], true);
+
+ // Malformed meta-tool arguments.
+ for args in [
+ json!({}),
+ json!({ "name": 7 }),
+ json!({ "name": "doc_list", "arguments": [1] }),
+ json!("doc_list"),
+ Value::Null,
+ json!({ "name": "tool_call" }),
+ json!({ "name": "tool_search" }),
+ ] {
+ let r = rpc(&mut s, 5, "tools/call", json!({ "name": "tool_call", "arguments": args }));
+ assert_eq!(r["result"]["isError"], true, "{args}");
+ assert!(!text(&r).is_empty());
+ }
+
+ // Direct calls keep the usual protocol error for an unknown tool, and the session survives all of it.
+ assert_eq!(rpc(&mut s, 6, "tools/call", json!({ "name": "nope" }))["error"]["code"], -32602);
+ assert_eq!(via_tool_call(&mut s, 7, "doc_open", json!({ "path": "a.pdf" }))["result"]["isError"], false);
+}
+
+#[cfg(feature = "mcp")]
+#[test]
+fn mcp_compact_tool_search_summarizes_the_first_sentence() {
+ let mut s = McpServer::new(Automation::new()).with_compact(true);
+ let mut summary = |tool: &str| {
+ let found = rpc(
+ &mut s,
+ 1,
+ "tools/call",
+ json!({ "name": "tool_search", "arguments": { "query": tool, "category": tool.split('_').next().unwrap() } }),
+ );
+ found["result"]["structuredContent"]["tools"].as_array().unwrap().iter().find(|t| t["name"] == tool).unwrap()["description"]
+ .as_str()
+ .unwrap()
+ .to_string()
+ };
+ // Abbreviations such as "e.g." do not end the summary.
+ assert_eq!(summary("page_number"), "Label a range of pages (e.g. i, ii, iii for front matter, or A-1, A-2 for an appendix).");
+ assert_eq!(
+ summary("accessibility_fix"),
+ "Apply the checker's automatic fix for a rule: primary-language (value: the language, e.g. en-US), title (value: the title; default the current title or file name; also shows it in the title bar) or tab-order (every page tabs in structure order)."
+ );
+}
+
+#[cfg(feature = "mcp")]
+#[test]
+fn mcp_compact_meta_tools_reject_unknown_arguments() {
+ let dir = workdir("mcp-compact-keys");
+ let mut s = compact_server(&dir);
+ let list = rpc(&mut s, 1, "tools/list", json!({}));
+ let metas = &list["result"]["tools"].as_array().unwrap()[10..];
+ assert_eq!(metas.len(), 2);
+ for meta in metas {
+ assert_eq!(meta["inputSchema"]["additionalProperties"], false, "{}", meta["name"]);
+ }
+ let text = |r: &Value| r["result"]["content"][0]["text"].as_str().unwrap_or_default().to_string();
+
+ // A misspelled filter is an error, not an unfiltered listing.
+ let typo = rpc(&mut s, 2, "tools/call", json!({ "name": "tool_search", "arguments": { "qurey": "rotate" } }));
+ assert_eq!(typo["result"]["isError"], true, "{typo}");
+ assert!(text(&typo).contains("\"qurey\"") && text(&typo).contains("query"), "{}", text(&typo));
+ let extra = rpc(&mut s, 3, "tools/call", json!({ "name": "tool_search", "arguments": { "query": "rotate", "extra": 1 } }));
+ assert_eq!(extra["result"]["isError"], true, "{extra}");
+ assert!(text(&extra).contains("\"extra\""), "{}", text(&extra));
+
+ // tool_call rejects extra outer keys before running anything.
+ let misspelled =
+ rpc(&mut s, 4, "tools/call", json!({ "name": "tool_call", "arguments": { "name": "doc_open", "argumentz": { "path": "a.pdf" } } }));
+ assert_eq!(misspelled["result"]["isError"], true, "{misspelled}");
+ assert!(text(&misspelled).contains("\"argumentz\""), "{}", text(&misspelled));
+ let extra = rpc(&mut s, 5, "tools/call", json!({ "name": "tool_call", "arguments": { "name": "doc_list", "unexpected": "value" } }));
+ assert_eq!(extra["result"]["isError"], true, "{extra}");
+ assert!(text(&extra).contains("\"unexpected\""), "{}", text(&extra));
+ assert_eq!(rpc(&mut s, 6, "tools/call", json!({ "name": "doc_list", "arguments": {} }))["result"]["structuredContent"]["documents"], json!([]));
+
+ // Keys inside "arguments" are left to the target tool, which rejects its unknown ones itself.
+ let inner = via_tool_call(&mut s, 7, "doc_list", json!({ "unexpected": "value" }));
+ assert_eq!(inner["result"]["isError"], true, "{inner}");
+ assert!(text(&inner).contains("doc_list: unknown argument \"unexpected\""), "{}", text(&inner));
+}
+
+#[cfg(feature = "mcp")]
+#[test]
+fn mcp_compact_tool_call_keeps_the_root_confinement() {
+ let root = workdir("mcp-compact-root");
+ let outside_dir = workdir("mcp-compact-outside");
+ let outside = outside_dir.join("a.pdf").to_string_lossy().into_owned();
+ let text = |r: &Value| r["result"]["content"][0]["text"].as_str().unwrap_or_default().to_string();
+
+ // Direct call and tool_call both refuse a real PDF outside the root, with the same words.
+ let mut confined = compact_server(&root);
+ let direct = rpc(&mut confined, 1, "tools/call", json!({ "name": "doc_open", "arguments": { "path": outside } }));
+ assert_eq!(direct["result"]["isError"], true, "{direct}");
+ assert!(text(&direct).contains("is outside the allowed directory"), "{}", text(&direct));
+ let wrapped = via_tool_call(&mut confined, 2, "doc_open", json!({ "path": outside }));
+ assert_eq!(wrapped["result"]["isError"], true, "{wrapped}");
+ assert_eq!(text(&wrapped), text(&direct));
+ // Nothing was opened.
+ let listed = rpc(&mut confined, 3, "tools/call", json!({ "name": "doc_list", "arguments": {} }));
+ assert_eq!(listed["result"]["structuredContent"]["documents"], json!([]));
+
+ // The same file opens through tool_call on a server without a root, so the refusal came from the root.
+ let mut open = McpServer::new(Automation::new()).with_compact(true);
+ let opened = via_tool_call(&mut open, 4, "doc_open", json!({ "path": outside }));
+ assert_eq!(opened["result"]["isError"], false, "{opened}");
+ assert_eq!(opened["result"]["structuredContent"]["pages"], 3);
+
+ // And a file inside the root still opens through the confined server.
+ assert_eq!(via_tool_call(&mut confined, 5, "doc_open", json!({ "path": "a.pdf" }))["result"]["isError"], false);
+}
+
#[test]
fn parallel_text_extraction_keeps_page_order_and_follows_edits() {
let dir = workdir("parallel");