mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-19 10:35:59 +00:00
Merge land/414 into land/451; keep main's MCP protocol versions, cap command_batch at 1000 steps
The 2026-07-28 revision and its resultType/ttlMs/cacheScope fields are dropped: main doesn't advertise them and they couldn't be checked against the spec. command_batch refuses more than 1000 steps. docs/mcp.md says that unknown argument keys are now refused with -32602 (a behaviour change for clients that sent extra keys). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
65f64c68cd
commit
79c0e249d7
6 files changed
+30
-50
No files matched your search
@@ -34,7 +34,7 @@ mcp::McpServer::new(a).serve(stdin, stdout)? // newline-delimited JS
|
||||
|
||||
`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 the common command/inspection/preview tools and 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 2026-07-28, 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.
|
||||
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
|
||||
|
||||
@@ -67,4 +67,4 @@ reported as an internal tool error, and the server continues serving.
|
||||
Exports complete synchronously. `progressToken` and cancellation notifications are harmlessly
|
||||
ignored; no background-job or cancellation behavior is added.
|
||||
|
||||
Session resources `pdfcraft://document` and `pdfcraft://commands` and modern result/cache hints are described in [docs/mcp.md](../../docs/mcp.md).
|
||||
Session resources `pdfcraft://document` and `pdfcraft://commands`, and the refusal of unknown argument keys, are described in [docs/mcp.md](../../docs/mcp.md).
|
||||
@@ -4,6 +4,9 @@ use serde_json::{Value, json};
|
||||
use crate::{Args, Automation, Content, Result, ToolError, encode_png, failed, info, tools};
|
||||
use pdfcraft_render::{RenderRequest, RequestKind};
|
||||
|
||||
/// The most steps one `command_batch` runs.
|
||||
pub(crate) const MAX_BATCH_STEPS: usize = 1000;
|
||||
|
||||
impl Automation {
|
||||
pub(crate) fn command_run(&mut self, args: &Args) -> Result<Vec<Content>> {
|
||||
let id = args.str("id")?;
|
||||
@@ -47,6 +50,9 @@ impl Automation {
|
||||
|
||||
pub(crate) fn command_batch(&mut self, args: &Args) -> Result<Value> {
|
||||
let steps = args.get("steps").and_then(Value::as_array).ok_or_else(|| ToolError::InvalidArgs("steps must be an array".into()))?;
|
||||
if steps.len() > MAX_BATCH_STEPS {
|
||||
return Err(ToolError::InvalidArgs(format!("a batch has at most {MAX_BATCH_STEPS} steps ({} given); split it", steps.len())));
|
||||
}
|
||||
// Check every envelope before applying any edit.
|
||||
for step in steps {
|
||||
let a = Args(step);
|
||||
|
||||
@@ -19,7 +19,7 @@ use serde_json::{Value, json};
|
||||
use crate::{Automation, Content, ToolError};
|
||||
|
||||
/// Protocol revisions we speak, newest first.
|
||||
pub const PROTOCOL_VERSIONS: &[&str] = &["2026-07-28", "2025-06-18", "2025-03-26", "2024-11-05"];
|
||||
pub const PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"];
|
||||
|
||||
const PARSE_ERROR: i64 = -32700;
|
||||
const INVALID_REQUEST: i64 = -32600;
|
||||
@@ -63,12 +63,11 @@ const TOOL_CALL: &str = "tool_call";
|
||||
pub struct McpServer {
|
||||
automation: Automation,
|
||||
compact: bool,
|
||||
modern: bool,
|
||||
}
|
||||
|
||||
impl McpServer {
|
||||
pub fn new(automation: Automation) -> Self {
|
||||
Self { automation, compact: false, modern: false }
|
||||
Self { automation, compact: false }
|
||||
}
|
||||
|
||||
/// In compact mode `tools/list` returns only [`COMPACT_CORE_TOOLS`] plus `tool_search` and
|
||||
@@ -119,22 +118,7 @@ impl McpServer {
|
||||
let id = id?; // notifications/initialized, notifications/cancelled, …: nothing to answer
|
||||
let result = if method == "tools/call" { guarded_tool(|| self.dispatch(method, ¶ms)) } else { self.dispatch(method, ¶ms) };
|
||||
Some(match result {
|
||||
Ok(mut result) => {
|
||||
let modern = params
|
||||
.get("_meta")
|
||||
.and_then(|m| m.get("io.modelcontextprotocol/protocolVersion"))
|
||||
.and_then(Value::as_str)
|
||||
.map_or(self.modern, |v| v == "2026-07-28");
|
||||
if modern
|
||||
&& matches!(method, "tools/list" | "resources/list" | "resources/templates/list" | "resources/read")
|
||||
&& let Some(object) = result.as_object_mut()
|
||||
{
|
||||
object.insert("resultType".into(), json!("complete"));
|
||||
object.insert("ttlMs".into(), json!(if matches!(method, "resources/read" | "resources/list") { 0 } else { 600_000 }));
|
||||
object.insert("cacheScope".into(), json!("private"));
|
||||
}
|
||||
json!({ "jsonrpc": "2.0", "id": id, "result": result })
|
||||
}
|
||||
Ok(result) => json!({ "jsonrpc": "2.0", "id": id, "result": result }),
|
||||
Err((code, message)) => error(id, code, &message),
|
||||
})
|
||||
}
|
||||
@@ -143,8 +127,7 @@ impl McpServer {
|
||||
match method {
|
||||
"initialize" => {
|
||||
let asked = params.get("protocolVersion").and_then(Value::as_str);
|
||||
let version = asked.filter(|v| PROTOCOL_VERSIONS.contains(v)).unwrap_or("2025-06-18");
|
||||
self.modern = version == "2026-07-28";
|
||||
let version = asked.filter(|v| PROTOCOL_VERSIONS.contains(v)).unwrap_or(PROTOCOL_VERSIONS[0]);
|
||||
Ok(json!({
|
||||
"protocolVersion": version,
|
||||
"capabilities": { "tools": { "listChanged": false }, "resources": { "listChanged": false, "subscribe": false } },
|
||||
|
||||
@@ -1054,7 +1054,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
.with(schema(json!({ "doc": doc(), "filter":{"type":"string"}, "enabled_only":{"type":"boolean"} }), &[])),
|
||||
t("command_run", "Run a command", "Run a registry command through its headless tool. Pass that tool's arguments in params (see command_list). Unknown params are ignored with warnings; path confinement still applies.")
|
||||
.destructive().with(schema(json!({"id":{"type":"string"},"params":{"type":"object"}}), &["id"])),
|
||||
t("command_batch", "Run several commands", "Run steps in order. Returns completed/failed counts and per-step ok/result/error; stop_on_error defaults to true.")
|
||||
t("command_batch", "Run several commands", "Run steps in order (at most 1000). Returns completed/failed counts and per-step ok/result/error; stop_on_error defaults to true.")
|
||||
.destructive().with(schema(json!({"steps":{"type":"array","items":schema(json!({"id":{"type":"string"},"params":{"type":"object"}}), &["id"])},"stop_on_error":{"type":"boolean"}}), &["steps"])),
|
||||
t("doc_inspect", "Inspect open documents", "With doc, return doc_info; otherwise return information for every open document (empty documents array when none are open).")
|
||||
.ro().with(schema(json!({"doc":doc()}), &[])),
|
||||
|
||||
@@ -3276,7 +3276,7 @@ fn conventions_annotations_and_strict_keys_in_both_modes() {
|
||||
|
||||
#[cfg(feature = "mcp")]
|
||||
#[test]
|
||||
fn conventions_resources_and_modern_results() {
|
||||
fn conventions_resources() {
|
||||
let dir = workdir("conventions-resources");
|
||||
let mut s = McpServer::new(auto(&dir));
|
||||
let read = |s: &mut McpServer, uri: &str| {
|
||||
@@ -3289,31 +3289,23 @@ fn conventions_resources_and_modern_results() {
|
||||
assert_eq!(read(&mut s, "pdfcraft://document"), doc["result"]["structuredContent"]);
|
||||
let commands = rpc(&mut s, 4, "tools/call", json!({"name":"command_list","arguments":{}}));
|
||||
assert_eq!(read(&mut s, "pdfcraft://commands"), commands["result"]["structuredContent"]);
|
||||
for (method, params) in [
|
||||
("tools/list", json!({})),
|
||||
("resources/list", json!({})),
|
||||
("resources/templates/list", json!({})),
|
||||
("resources/read", json!({"uri":"pdfcraft://document"})),
|
||||
] {
|
||||
let legacy = rpc(&mut s, 5, method, params.clone());
|
||||
assert!(legacy["result"].get("resultType").is_none());
|
||||
let mut modern = params;
|
||||
modern["_meta"] = json!({"io.modelcontextprotocol/protocolVersion":"2026-07-28"});
|
||||
let r = rpc(&mut s, 6, method, modern);
|
||||
assert_eq!(r["result"]["resultType"], "complete");
|
||||
assert_eq!(r["result"]["cacheScope"], "private");
|
||||
assert_eq!(r["result"]["ttlMs"], if method == "resources/read" || method == "resources/list" { 0 } else { 600_000 });
|
||||
let mut stripped = r["result"].clone();
|
||||
for k in ["resultType", "ttlMs", "cacheScope"] {
|
||||
stripped.as_object_mut().unwrap().remove(k);
|
||||
}
|
||||
assert_eq!(stripped, legacy["result"]);
|
||||
// Responses keep the shape every supported protocol revision expects: no cache hints.
|
||||
for (method, params) in [("tools/list", json!({})), ("resources/list", json!({})), ("resources/read", json!({"uri":"pdfcraft://document"}))] {
|
||||
assert!(rpc(&mut s, 5, method, params)["result"].get("resultType").is_none());
|
||||
}
|
||||
assert_eq!(rpc(&mut s, 7, "initialize", json!({"protocolVersion":"2026-07-28"}))["result"]["protocolVersion"], "2026-07-28");
|
||||
assert_eq!(rpc(&mut s, 8, "tools/list", json!({}))["result"]["resultType"], "complete");
|
||||
assert_eq!(rpc(&mut s, 7, "initialize", json!({"protocolVersion":"2026-07-28"}))["result"]["protocolVersion"], "2025-06-18");
|
||||
assert!(s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":999}}"#).is_none());
|
||||
assert_eq!(
|
||||
rpc(&mut s, 9, "tools/call", json!({"name":"doc_inspect","arguments":{},"_meta":{"progressToken":"quick"}}))["result"]["isError"],
|
||||
false
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_batch_refuses_more_than_a_thousand_steps() {
|
||||
let dir = workdir("batch-cap");
|
||||
let mut a = auto(&dir);
|
||||
let steps: Vec<Value> = (0..1001).map(|_| json!({"id":"no.such.command"})).collect();
|
||||
let err = a.call("command_batch", &json!({"steps": steps})).unwrap_err();
|
||||
assert!(err.to_string().contains("at most 1000 steps"), "{err}");
|
||||
}
|
||||
+3
-4
@@ -40,7 +40,6 @@ arguments), including an empty `documents` array before any PDF is opened. `pdfc
|
||||
returns the command catalog (as `command_list`). Existing per-document info, text and page-image
|
||||
resources and their templates are preserved.
|
||||
|
||||
MCP 2026-07-28 clients, negotiated through `initialize` or a request's `_meta`, receive
|
||||
`resultType: "complete"`, `ttlMs`, and `cacheScope: "private"` on lists and reads. Resource reads
|
||||
and the changing list of open-document resources have zero TTL; tool and template catalogs use
|
||||
ten minutes. Older clients keep their previous response shape.
|
||||
Unknown top-level argument keys are refused with JSON-RPC `-32602` (invalid params) instead of
|
||||
being ignored, so a misspelled argument is reported rather than silently dropped. Clients that
|
||||
sent extra keys before get an error now.
|
||||
Reference in new issue
Block a user