Skip to content

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

M10: MCP resources for open documents: information, text, page text and page images (resources/list, templates, read)

Brandon Thomasf1817459f204
diff --git a/crates/automation/src/mcp.rs b/crates/automation/src/mcp.rs
index 86f9b2cc2..bfa335444 100644
--- a/crates/automation/src/mcp.rs
+++ b/crates/automation/src/mcp.rs
@@ -5,8 +5,10 @@
//! configuration), and stops when its input closes. It opens no network port; the transport is
//! newline-delimited JSON-RPC 2.0 over stdin/stdout.
//!
-//! Implemented: `initialize`, `ping`, `tools/list`, `tools/call`, and the `notifications/*` the
-//! client sends. Tool failures are reported in the result (`isError: true`) so the agent can read
+//! Implemented: `initialize`, `ping`, `tools/list`, `tools/call`, `resources/list`,
+//! `resources/templates/list`, `resources/read`, and the `notifications/*` the client sends.
+//! Resources expose the open documents read-only: `printcraft://doc/{doc}/info` (JSON),
+//! `…/text` (plain text), `…/page/{page}/text` and `…/page/{page}/image` (PNG; `?dpi=` 1–600). Tool failures are reported in the result (`isError: true`) so the agent can read
//! them; protocol errors use JSON-RPC error codes.
use std::io::{BufRead, Write};
@@ -26,7 +28,8 @@ const INVALID_PARAMS: i64 = -32602;
const INSTRUCTIONS: &str = "PrintCraft edits PDFs. Open a file with doc_open to get a document id, then inspect \
(doc_info, text_extract, text_find, page_render) or edit it (page_*, doc_set_info). Edits are undoable \
-(edit_undo) and stay in memory until doc_save. Page numbers are 1-based.";
+(edit_undo) and stay in memory until doc_save. Page numbers are 1-based. Open documents are also \
+resources: printcraft://doc/{doc}/info, /text, /page/{page}/text and /page/{page}/image.";
pub struct McpServer {
automation: Automation,
@@ -88,7 +91,7 @@ impl McpServer {
let version = asked.filter(|v| PROTOCOL_VERSIONS.contains(v)).unwrap_or(PROTOCOL_VERSIONS[0]);
Ok(json!({
"protocolVersion": version,
- "capabilities": { "tools": { "listChanged": false } },
+ "capabilities": { "tools": { "listChanged": false }, "resources": { "listChanged": false, "subscribe": false } },
"serverInfo": { "name": "printcraft", "title": "PrintCraft", "version": env!("CARGO_PKG_VERSION"), "websiteUrl": printcraft_engine::links::APP_PAGE },
"instructions": INSTRUCTIONS,
}))
@@ -104,11 +107,121 @@ impl McpServer {
Err(e) => Ok(json!({ "content": [{ "type": "text", "text": e.to_string() }], "isError": true })),
}
}
+ "resources/list" => Ok(json!({ "resources": self.resource_list() })),
+ "resources/templates/list" => Ok(json!({ "resourceTemplates": resource_templates() })),
+ "resources/read" => {
+ let uri = params.get("uri").and_then(Value::as_str).ok_or((INVALID_PARAMS, "resources/read needs a uri".to_string()))?;
+ self.read_resource(uri).map(|c| json!({ "contents": [c] }))
+ }
other => Err((METHOD_NOT_FOUND, format!("method not found: {other}"))),
}
}
}
+/// The resource behind a `printcraft://` URI.
+#[derive(Debug, PartialEq)]
+enum Resource {
+ Info(u64),
+ Text(u64),
+ PageText(u64, u64),
+ PageImage(u64, u64, Option<f64>),
+}
+
+fn parse_uri(uri: &str) -> Option<Resource> {
+ let rest = uri.strip_prefix("printcraft://doc/")?;
+ let (path, query) = rest.split_once('?').unwrap_or((rest, ""));
+ let dpi = query.split('&').find_map(|kv| kv.strip_prefix("dpi=")).and_then(|v| v.parse::<f64>().ok());
+ let parts: Vec<&str> = path.split('/').collect();
+ let doc = parts.first()?.parse().ok()?;
+ match parts[1..] {
+ ["info"] => Some(Resource::Info(doc)),
+ ["text"] => Some(Resource::Text(doc)),
+ ["page", p, "text"] => Some(Resource::PageText(doc, p.parse().ok()?)),
+ ["page", p, "image"] => Some(Resource::PageImage(doc, p.parse().ok()?, dpi)),
+ _ => None,
+ }
+}
+
+fn resource_templates() -> Value {
+ json!([
+ { "uriTemplate": "printcraft://doc/{doc}/info", "name": "Document information", "mimeType": "application/json",
+ "description": "Metadata, pages, bookmarks, annotations, fields, links, layers, attachments, fonts and security of an open document (as doc_info)." },
+ { "uriTemplate": "printcraft://doc/{doc}/text", "name": "Document text", "mimeType": "text/plain",
+ "description": "The text of every page in reading order, each page under a \"Page n\" heading." },
+ { "uriTemplate": "printcraft://doc/{doc}/page/{page}/text", "name": "Page text", "mimeType": "text/plain",
+ "description": "The text of one page (1-based) in reading order." },
+ { "uriTemplate": "printcraft://doc/{doc}/page/{page}/image{?dpi}", "name": "Page image", "mimeType": "image/png",
+ "description": "One page (1-based) rendered to PNG; dpi 1–600, default 96." },
+ ])
+}
+
+impl McpServer {
+ fn resource_list(&mut self) -> Vec<Value> {
+ let docs = self.automation.call("doc_list", &json!({})).ok().and_then(|c| match c.into_iter().next() {
+ Some(Content::Json(v)) => v["documents"].as_array().cloned(),
+ _ => None,
+ });
+ let mut out = Vec::new();
+ for d in docs.unwrap_or_default() {
+ let (id, name) = (d["doc"].as_u64().unwrap_or(0), d["name"].as_str().unwrap_or("document"));
+ out.push(
+ json!({ "uri": format!("printcraft://doc/{id}/info"), "name": format!("{name} (information)"), "mimeType": "application/json" }),
+ );
+ out.push(json!({ "uri": format!("printcraft://doc/{id}/text"), "name": format!("{name} (text)"), "mimeType": "text/plain" }));
+ // Pages are listed for short documents; longer ones use the templates.
+ let pages = d["pages"].as_u64().unwrap_or(0);
+ if pages <= 50 {
+ for p in 1..=pages {
+ out.push(json!({ "uri": format!("printcraft://doc/{id}/page/{p}/image"), "name": format!("{name}, page {p}"), "mimeType": "image/png" }));
+ }
+ }
+ }
+ out
+ }
+
+ fn read_resource(&mut self, uri: &str) -> Result<Value, (i64, String)> {
+ let r = parse_uri(uri).ok_or((INVALID_PARAMS, format!("unknown resource {uri:?}")))?;
+ let call = |a: &mut Automation, tool: &str, args: Value| a.call(tool, &args).map_err(|e| (INVALID_PARAMS, e.to_string()));
+ let json_of = |c: Vec<Content>| c.into_iter().find_map(|c| if let Content::Json(v) = c { Some(v) } else { None }).unwrap_or(Value::Null);
+ let text_of = |v: &Value, headings: bool| {
+ let pages = v["pages"].as_array().cloned().unwrap_or_default();
+ let parts: Vec<String> = pages
+ .iter()
+ .map(|p| {
+ let t = p["text"].as_str().unwrap_or("");
+ if headings { format!("Page {}\n{t}", p["page"]) } else { t.to_owned() }
+ })
+ .collect();
+ parts.join("\n\n")
+ };
+ Ok(match r {
+ Resource::Info(doc) => {
+ let v = json_of(call(&mut self.automation, "doc_info", json!({ "doc": doc }))?);
+ json!({ "uri": uri, "mimeType": "application/json", "text": serde_json::to_string_pretty(&v).unwrap_or_default() })
+ }
+ Resource::Text(doc) => {
+ let v = json_of(call(&mut self.automation, "text_extract", json!({ "doc": doc }))?);
+ json!({ "uri": uri, "mimeType": "text/plain", "text": text_of(&v, true) })
+ }
+ Resource::PageText(doc, page) => {
+ let v = json_of(call(&mut self.automation, "text_extract", json!({ "doc": doc, "pages": [page] }))?);
+ json!({ "uri": uri, "mimeType": "text/plain", "text": text_of(&v, false) })
+ }
+ Resource::PageImage(doc, page, dpi) => {
+ let mut args = json!({ "doc": doc, "page": page });
+ if let Some(d) = dpi {
+ args["dpi"] = json!(d);
+ }
+ let png = call(&mut self.automation, "page_render", args)?
+ .into_iter()
+ .find_map(|c| if let Content::Png { data, .. } = c { Some(data) } else { None });
+ let png = png.ok_or((INVALID_PARAMS, "the page could not be rendered".to_string()))?;
+ json!({ "uri": uri, "mimeType": "image/png", "blob": base64::engine::general_purpose::STANDARD.encode(png) })
+ }
+ })
+ }
+}
+
fn error(id: Value, code: i64, message: &str) -> Value {
json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } })
}
@@ -146,3 +259,17 @@ fn call_result(content: Vec<Content>) -> Value {
}
result
}
+
+#[cfg(test)]
+mod tests {
+ use super::{Resource, parse_uri};
+
+ #[test]
+ fn resource_uris_parse() {
+ assert_eq!(parse_uri("printcraft://doc/3/info"), Some(Resource::Info(3)));
+ assert_eq!(parse_uri("printcraft://doc/3/page/2/image?dpi=36"), Some(Resource::PageImage(3, 2, Some(36.0))));
+ assert_eq!(parse_uri("printcraft://doc/3/page/2/text"), Some(Resource::PageText(3, 2)));
+ assert_eq!(parse_uri("printcraft://doc/x/info"), None);
+ assert_eq!(parse_uri("file:///etc/passwd"), None);
+ }
+}
diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rs
index 225df17ed..a9fd00c32 100644
--- a/crates/automation/tests/automation.rs
+++ b/crates/automation/tests/automation.rs
@@ -277,7 +277,8 @@ fn mcp_errors() {
let mut s = McpServer::new(Automation::new());
assert_eq!(rpc(&mut s, 1, "initialize", json!({ "protocolVersion": "1999-01-01" }))["result"]["protocolVersion"], "2025-06-18");
assert_eq!(rpc(&mut s, 2, "ping", json!({}))["result"], json!({}));
- assert_eq!(rpc(&mut s, 3, "resources/list", json!({}))["error"]["code"], -32601);
+ assert_eq!(rpc(&mut s, 3, "prompts/list", json!({}))["error"]["code"], -32601);
+ assert_eq!(rpc(&mut s, 6, "resources/read", json!({ "uri": "printcraft://doc/9/info" }))["error"]["code"], -32602);
assert_eq!(rpc(&mut s, 4, "tools/call", json!({ "name": "nope" }))["error"]["code"], -32602);
let failed = rpc(&mut s, 5, "tools/call", json!({ "name": "doc_open", "arguments": { "path": "/definitely/not/here.pdf" } }));
assert_eq!(failed["result"]["isError"], true);
@@ -286,6 +287,32 @@ fn mcp_errors() {
assert_eq!(bad["error"]["code"], -32700);
}
+#[cfg(feature = "mcp")]
+#[test]
+fn mcp_resources_expose_open_documents() {
+ let dir = workdir("mcp-resources");
+ let mut s = McpServer::new(auto(&dir));
+ assert!(rpc(&mut s, 1, "initialize", json!({}))["result"]["capabilities"]["resources"].is_object());
+ assert_eq!(rpc(&mut s, 2, "resources/list", json!({}))["result"]["resources"], json!([]));
+ assert_eq!(rpc(&mut s, 3, "resources/templates/list", json!({}))["result"]["resourceTemplates"].as_array().unwrap().len(), 4);
+ rpc(&mut s, 4, "tools/call", json!({ "name": "doc_open", "arguments": { "path": "a.pdf" } }));
+ let list = rpc(&mut s, 5, "resources/list", json!({}))["result"]["resources"].as_array().cloned().unwrap();
+ assert_eq!(list.len(), 2 + 3, "info, text and three page images");
+ assert_eq!(list[0]["uri"], "printcraft://doc/1/info");
+ let read = |s: &mut McpServer, uri: &str| rpc(s, 6, "resources/read", json!({ "uri": uri }))["result"]["contents"][0].clone();
+ let text = read(&mut s, "printcraft://doc/1/text");
+ assert_eq!(text["mimeType"], "text/plain");
+ assert!(text["text"].as_str().unwrap().contains("Page 2\nPage 2"), "{text}");
+ assert_eq!(read(&mut s, "printcraft://doc/1/page/3/text")["text"], "Page 3");
+ let info: Value = serde_json::from_str(read(&mut s, "printcraft://doc/1/info")["text"].as_str().unwrap()).unwrap();
+ assert_eq!(info["pages"].as_array().unwrap().len(), 3);
+ let img = read(&mut s, "printcraft://doc/1/page/1/image?dpi=36");
+ use base64::Engine as _;
+ let png = base64::engine::general_purpose::STANDARD.decode(img["blob"].as_str().unwrap()).unwrap();
+ assert_eq!(&png[1..4], b"PNG");
+ assert_eq!(rpc(&mut s, 7, "resources/read", json!({ "uri": "printcraft://doc/1/page/9/image" }))["error"]["code"], -32602);
+}
+
#[test]
fn parallel_text_extraction_keeps_page_order_and_follows_edits() {
let dir = workdir("parallel");
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index a626fdc10..2f201678e 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -9323,11 +9323,11 @@ title = "MCP resources for page images and text"
area = "N"
tier = "P1"
milestone = "M13"
-status = "planned"
+status = "shipped"
commands = []
-tools = []
-evidence = []
-notes = ""
+tools = ["doc_info", "text_extract", "page_render"]
+evidence = ["crates/automation/tests/automation.rs::mcp_resources_expose_open_documents", "crates/automation/src/mcp.rs::resource_uris_parse"]
+notes = "resources/list, resources/templates/list and resources/read: printcraft://doc/{doc}/info (JSON), /text, /page/{page}/text, /page/{page}/image?dpi= (PNG)"
[[feature]]
id = "misc.ui-control-channel"