Skip to main content

docling_cli/
mcp.rs

1//! `docling-rs mcp` (#669): a [Model Context Protocol](https://modelcontextprotocol.io)
2//! server, so agents — Claude Desktop, Claude Code, IDE assistants — call
3//! docling.rs directly.
4//!
5//! Three tools:
6//!
7//! - `convert_to_markdown(uri)` — MarkItDown's MCP tool (`markitdown-mcp`),
8//!   same name and contract, so a config that pointed at MarkItDown keeps
9//!   working: the document behind an `http:`/`https:`/`file:`/`data:` URI as
10//!   Markdown. A plain path is accepted too.
11//! - `convert(uri, to?, images?, options?)` — any output format docling.rs
12//!   writes as text, with the conversion options every other surface takes
13//!   ([`docling::ConvertOptions`], docs/OPTIONS.md).
14//! - `list_input_formats()` — the extensions this binary converts.
15//!
16//! Transports: stdio (the default — what a desktop client launches) or
17//! Streamable HTTP with `--http` (`/mcp` on `--host`/`--port`, 127.0.0.1:3001
18//! by default), both through rmcp, the protocol's official Rust SDK.
19//!
20//! The server reads files and, when allowed, the network on behalf of a
21//! model, whose inputs may be steered by the documents it reads — so what a
22//! call can reach is the operator's decision, made on the command line:
23//!
24//! - local reads are confined to `--root DIR` (repeatable; the working
25//!   directory by default) — paths are checked lexically first, so a probe
26//!   outside the root learns nothing about what exists there, then after
27//!   resolving symlinks;
28//! - URLs are fetched only with `--allow-url-fetch`, through
29//!   [`docling::fetch`]: the SSRF block-list on every redirect hop, a size
30//!   cap (`DOCLING_RS_MAX_FETCH_BYTES`, 256 MiB) and timeouts. The options
31//!   that reach the network on their own — remote `<img src>`
32//!   (`image_sources=remote`), a request-supplied `vlm_endpoint`, the
33//!   headless browser — sit behind the same flag, docling-serve's rules;
34//!   options that name files (`xbrl_taxonomy`, a copybook path in
35//!   `ebcdic_layout`) are held to the root;
36//! - `--http` binds loopback unless `--allow-remote`, checks the `Host`
37//!   header (DNS rebinding) and the browser `Origin` on a loopback bind, and
38//!   takes an optional bearer token (`--bearer-token` /
39//!   `DOCLING_RS_MCP_TOKEN`).
40//!
41//! Conversions run on the blocking pool, at most `--concurrency` (2) at a
42//! time; a call that carries a progress token gets a heartbeat
43//! `notifications/progress` every 10 s, so clients that reset their request
44//! timeout on progress wait out a long PDF. stdout is the stdio transport's
45//! wire — everything else the process says goes to stderr.
46//!
47//! The same server runs from the `docling-rs` binary ([`run`]) and from
48//! embedders such as the Python package's `docling-rs-mcp` launcher
49//! ([`run_with`] and a [`Launcher`] naming the command and where its PDF
50//! models come from).
51
52use std::path::{Component, Path, PathBuf};
53use std::process::ExitCode;
54use std::sync::atomic::{AtomicBool, Ordering};
55use std::sync::Arc;
56use std::time::Duration;
57
58use docling::{ConvertOptions, DocumentConverter, ImageMode, InputFormat, SourceDocument};
59use rmcp::handler::server::router::tool::ToolRouter;
60use rmcp::handler::server::wrapper::Parameters;
61use rmcp::model::{Implementation, ProgressNotificationParam, ServerCapabilities, ServerConfig};
62use rmcp::service::RequestContext;
63use rmcp::{tool, tool_handler, tool_router, RoleServer, ServerHandler, ServiceExt};
64use serde::Deserialize;
65
66/// How the server presents itself: the command that starts it (in `--help`,
67/// usage errors and the startup line), the client configuration `--help`
68/// shows, and how to get the PDF models when they are missing. The binary
69/// uses [`Launcher::CLI`].
70#[derive(Clone, Copy, Debug)]
71pub struct Launcher<'a> {
72    /// The command line that starts the server, e.g. `docling-rs mcp`.
73    pub command: &'a str,
74    /// A Claude Desktop `mcpServers` entry that launches it.
75    pub client_config: &'a str,
76    /// The sentence that tells the operator how to fetch the layout models.
77    pub models_hint: &'a str,
78    /// Flags the launcher handles itself, listed in `--help` (empty for none).
79    pub extra_flags: &'a str,
80}
81
82impl Launcher<'static> {
83    /// The `docling-rs` binary's `mcp` subcommand.
84    pub const CLI: Self = Self {
85        command: "docling-rs mcp",
86        client_config: "{\"mcpServers\": {\"docling\": {\"command\": \"docling-rs\",\n     \"args\": [\"mcp\", \"--root\", \"/Users/me/Documents\"]}}}",
87        models_hint: "Fetch them with scripts/install/download_dependencies.sh (--cli \
88                      beside a cargo-installed binary), or point DOCLING_RS_MODELS_DIR at a \
89                      .models directory.",
90        extra_flags: "",
91    };
92}
93
94fn help(launcher: &Launcher) -> String {
95    let cmd = launcher.command;
96    let pad = " ".repeat(cmd.len());
97    format!(
98        "\
99{cmd} — a Model Context Protocol server over the docling.rs converter
100
101usage: {cmd} [--root DIR]... [--allow-url-fetch] [--concurrency N]
102       {cmd} --http [--host HOST] [--port PORT] [--allow-remote]
103       {pad} [--bearer-token TOKEN] [...]
104
105Tools: convert_to_markdown(uri) (MarkItDown's MCP tool, same contract),
106convert(uri, to, images, options), list_input_formats().
107
108  --root DIR          directory local paths and file: URIs may read from;
109                      repeatable (default: the working directory)
110  --allow-url-fetch   convert http(s) URLs, remote <img src> and a
111                      request-supplied vlm_endpoint (outbound requests from
112                      this machine; private and loopback targets stay refused
113                      unless DOCLING_RS_ALLOW_PRIVATE_IP_FETCH=1)
114  --concurrency N     conversions running at once (default 2)
115  --http              serve Streamable HTTP at /mcp instead of stdio
116  --host HOST         bind address for --http (default 127.0.0.1)
117  --port PORT         port for --http (default 3001)
118  --allow-remote      let --http bind a non-loopback address
119  --bearer-token T    require `Authorization: Bearer T` on --http
120                      (default: DOCLING_RS_MCP_TOKEN when set)
121{}
122Claude Desktop (claude_desktop_config.json):
123  {}",
124        if launcher.extra_flags.is_empty() {
125            String::new()
126        } else {
127            format!("{}\n", launcher.extra_flags.trim_end())
128        },
129        launcher.client_config
130    )
131}
132
133/// A `--root` directory in both spellings a path may arrive in: as the
134/// operator gave it (absolute, `..` folded — what an agent quotes back) and
135/// canonical (symlinks resolved: macOS's `/tmp` is `/private/tmp`, Windows
136/// adds a `\\?\` prefix).
137struct Root {
138    given: PathBuf,
139    canonical: PathBuf,
140}
141
142impl Root {
143    fn new(dir: &str) -> Result<Self, String> {
144        let canonical = std::fs::canonicalize(dir).map_err(|e| format!("--root {dir}: {e}"))?;
145        if !canonical.is_dir() {
146            return Err(format!("--root {dir}: not a directory"));
147        }
148        let given = std::path::absolute(dir).map_err(|e| format!("--root {dir}: {e}"))?;
149        Ok(Self {
150            given: normalize(&given),
151            canonical,
152        })
153    }
154}
155
156/// What the operator allowed, shared by every session.
157struct State {
158    /// The directories local reads are confined to; the first one resolves
159    /// relative paths.
160    roots: Vec<Root>,
161    allow_url_fetch: bool,
162    /// How `http(s)` inputs are fetched (only with `--allow-url-fetch`).
163    fetch_policy: docling::FetchPolicy,
164    permits: Arc<tokio::sync::Semaphore>,
165    /// The missing-models note is printed once per process.
166    warned_text_layer: AtomicBool,
167    /// The command that started the server, for the stderr notes.
168    command: String,
169    /// How to get the layout models when they are missing.
170    models_hint: String,
171    /// The PDF/image models, loaded on the first call that needs them and
172    /// kept for the next — docling-serve's warm pipeline, shared by every
173    /// session of this process.
174    warm: docling::WarmPipeline,
175}
176
177struct HttpConfig {
178    host: String,
179    port: u16,
180    allow_remote: bool,
181    token: Option<String>,
182}
183
184/// `docling-rs mcp …` — parse the flags, then serve until the client hangs
185/// up (stdio) or Ctrl-C (HTTP).
186pub fn run(args: Vec<String>) -> ExitCode {
187    ExitCode::from(run_with(args, &Launcher::CLI))
188}
189
190/// [`run`] for an embedder: the flags after the command, how the server
191/// should name itself; returns the process exit status (0, 1 on a serving
192/// error, 2 on a usage error). Call it before other threads read the
193/// environment — it defaults `DOCLING_RS_NO_ARENA`.
194pub fn run_with(args: Vec<String>, launcher: &Launcher) -> u8 {
195    // A long-lived server holding warm ONNX sessions, like `serve` (#263):
196    // the CPU arena off unless the operator says otherwise. Measured on the
197    // warm MCP server (4 vCPU, a 9-page paper and two short PDFs in turn):
198    // 2.1 GB live with the arena, 0.55 GB — the models — without, at the
199    // same latency.
200    if std::env::var_os("DOCLING_RS_NO_ARENA").is_none() {
201        std::env::set_var("DOCLING_RS_NO_ARENA", "1");
202    }
203    let usage = |err: &str| usage(launcher, err);
204    let mut roots: Vec<String> = Vec::new();
205    let mut allow_url_fetch = false;
206    let mut concurrency: usize = 2;
207    let mut http = false;
208    let mut host = "127.0.0.1".to_string();
209    let mut port: u16 = 3001;
210    let mut allow_remote = false;
211    let mut token = docling_core::env::nonempty("DOCLING_RS_MCP_TOKEN");
212    // The `--http`-only flags, so a stdio launch that carries one fails
213    // loudly instead of ignoring it.
214    let mut http_flag: Option<&'static str> = None;
215    let args = match split_flag_values(args) {
216        Ok(args) => args,
217        Err(e) => return usage(&e),
218    };
219    let mut it = args.into_iter();
220    while let Some(arg) = it.next() {
221        match arg.as_str() {
222            "--help" | "-h" => {
223                println!("{}", help(launcher));
224                return 0;
225            }
226            "--root" => match it.next() {
227                Some(v) if !v.is_empty() => roots.push(v),
228                _ => return usage("--root needs a directory"),
229            },
230            "--allow-url-fetch" => allow_url_fetch = true,
231            "--concurrency" => match it.next().and_then(|v| v.parse().ok()) {
232                Some(n) if n >= 1 => concurrency = n,
233                _ => return usage("--concurrency needs a positive integer"),
234            },
235            "--http" => http = true,
236            "--host" => match it.next() {
237                Some(v) if !v.is_empty() => {
238                    host = v;
239                    http_flag = Some("--host");
240                }
241                _ => return usage("--host needs an address"),
242            },
243            "--port" => match it.next().and_then(|v| v.parse().ok()) {
244                Some(p) => {
245                    port = p;
246                    http_flag = Some("--port");
247                }
248                None => return usage("--port needs a port number"),
249            },
250            "--allow-remote" => {
251                allow_remote = true;
252                http_flag = Some("--allow-remote");
253            }
254            "--bearer-token" => match it.next() {
255                Some(v) if !v.is_empty() => {
256                    token = Some(v);
257                    http_flag = Some("--bearer-token");
258                }
259                _ => return usage("--bearer-token needs a token"),
260            },
261            other => return usage(&format!("unknown argument '{other}'")),
262        }
263    }
264    if let (false, Some(flag)) = (http, http_flag) {
265        return usage(&format!("{flag} applies to --http only"));
266    }
267    let defaulted = roots.is_empty();
268    if defaulted {
269        roots.push(".".to_string());
270    }
271    let roots = match roots
272        .iter()
273        .map(|r| Root::new(r))
274        .collect::<Result<Vec<_>, _>>()
275    {
276        Ok(roots) => roots,
277        Err(e) => return usage(&e),
278    };
279    // Desktop clients often start servers in `/`: the working-directory
280    // default would then open the whole file system. That takes an explicit
281    // `--root`.
282    if defaulted && roots[0].canonical.parent().is_none() {
283        return usage(&format!(
284            "the working directory is the file system root ({}); pass --root DIR \
285             to choose what the server may read",
286            roots[0].canonical.display()
287        ));
288    }
289    let state = Arc::new(State {
290        roots,
291        allow_url_fetch,
292        fetch_policy: fetch_policy(),
293        permits: Arc::new(tokio::sync::Semaphore::new(concurrency)),
294        warned_text_layer: AtomicBool::new(false),
295        command: launcher.command.to_string(),
296        models_hint: launcher.models_hint.to_string(),
297        warm: docling::WarmPipeline::new(),
298    });
299    // A long-lived process: large buffers are mapped and returned, not
300    // carved from the per-thread arenas where they stay resident.
301    docling::memory::pin_mmap_threshold();
302    let runtime = match tokio::runtime::Runtime::new() {
303        Ok(rt) => rt,
304        Err(e) => {
305            eprintln!("error: tokio runtime: {e}");
306            return 1;
307        }
308    };
309    let result = if http {
310        let cfg = HttpConfig {
311            host,
312            port,
313            allow_remote,
314            token,
315        };
316        runtime.block_on(serve_http(state, cfg))
317    } else {
318        runtime.block_on(serve_stdio(state))
319    };
320    // A conversion still running for a client that hung up has no one to
321    // answer: exit now rather than wait for it.
322    runtime.shutdown_background();
323    match result {
324        Ok(()) => 0,
325        Err(e) => {
326            eprintln!("error: {e}");
327            1
328        }
329    }
330}
331
332/// The `--flag=value` spelling next to `--flag value`, so the argument
333/// lists MCP catalogs generate work (the registry's `server.json` describes
334/// a named argument as `--flag={value}`): value flags split in two, the
335/// switches take `=true` / `=false`.
336fn split_flag_values(args: Vec<String>) -> Result<Vec<String>, String> {
337    const SWITCHES: [&str; 3] = ["--allow-url-fetch", "--http", "--allow-remote"];
338    let mut out = Vec::with_capacity(args.len());
339    for arg in args {
340        let Some((flag, value)) = arg.split_once('=').filter(|(f, _)| f.starts_with("--")) else {
341            out.push(arg);
342            continue;
343        };
344        if SWITCHES.contains(&flag) {
345            match value.to_ascii_lowercase().as_str() {
346                "" | "true" | "1" | "yes" | "on" => out.push(flag.to_string()),
347                "false" | "0" | "no" | "off" => {}
348                _ => return Err(format!("{flag} takes true or false, not '{value}'")),
349            }
350        } else {
351            out.push(flag.to_string());
352            out.push(value.to_string());
353        }
354    }
355    Ok(out)
356}
357
358fn usage(launcher: &Launcher, err: &str) -> u8 {
359    eprintln!("error: {err}");
360    eprintln!(
361        "usage: {} [--root DIR]... [--allow-url-fetch] [--concurrency N] [--http [--host HOST] [--port PORT] [--allow-remote] [--bearer-token TOKEN]]",
362        launcher.command
363    );
364    2
365}
366
367/// One line on stderr saying what this server may reach — the operator's
368/// check that the flags did what they meant.
369fn describe(state: &State, transport: &str) {
370    eprintln!(
371        "{} {} · {transport} · root {} · URL fetch {}",
372        state.command,
373        env!("CARGO_PKG_VERSION"),
374        state.roots_display(),
375        if state.allow_url_fetch { "on" } else { "off" }
376    );
377}
378
379impl State {
380    /// The roots as the operator gave them, comma-separated.
381    fn roots_display(&self) -> String {
382        let roots: Vec<String> = self
383            .roots
384            .iter()
385            .map(|r| r.given.display().to_string())
386            .collect();
387        roots.join(", ")
388    }
389}
390
391async fn serve_stdio(state: Arc<State>) -> Result<(), String> {
392    describe(&state, "stdio");
393    let service = DoclingMcp::new(state)
394        .serve(rmcp::transport::stdio())
395        .await
396        .map_err(|e| format!("mcp: {e}"))?;
397    service
398        .waiting()
399        .await
400        .map(|_| ())
401        .map_err(|e| format!("mcp: {e}"))
402}
403
404async fn serve_http(state: Arc<State>, cfg: HttpConfig) -> Result<(), String> {
405    use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
406    use rmcp::transport::streamable_http_server::{
407        StreamableHttpServerConfig, StreamableHttpService,
408    };
409
410    let addr = tokio::net::lookup_host((cfg.host.as_str(), cfg.port))
411        .await
412        .map_err(|e| format!("--host {}: {e}", cfg.host))?
413        .next()
414        .ok_or_else(|| format!("--host {}: no address", cfg.host))?;
415    let loopback = addr.ip().is_loopback();
416    if !loopback && !cfg.allow_remote {
417        return Err(format!(
418            "refusing to bind {addr}: not a loopback address — the server reads files under \
419             its root for whoever can reach it; pass --allow-remote (and --bearer-token) to \
420             expose it"
421        ));
422    }
423    if !loopback && cfg.token.is_none() {
424        eprintln!(
425            "warning: serving {addr} without a bearer token — anyone who can reach it can \
426             read the files under the root"
427        );
428    }
429    let mut config = StreamableHttpServerConfig::default();
430    // Ctrl-C closes the open sessions as well as the listener.
431    let ct = config.cancellation_token.clone();
432    config = if loopback {
433        // The default allowed `Host`s (localhost, 127.0.0.1, ::1) stop DNS
434        // rebinding; the `Origin` list stops a web page in the user's own
435        // browser from driving the server — requests without an `Origin`
436        // (every non-browser client) pass.
437        config.with_allowed_origins(["http://localhost:*", "http://127.0.0.1:*", "http://[::1]:*"])
438    } else {
439        // Remote clients name the server by its own host name; the bearer
440        // token is the control there.
441        config.disable_allowed_hosts()
442    };
443    let service: StreamableHttpService<DoclingMcp, LocalSessionManager> =
444        StreamableHttpService::new(
445            {
446                let state = state.clone();
447                move || Ok(DoclingMcp::new(state.clone()))
448            },
449            Default::default(),
450            config,
451        );
452    let mut router = axum::Router::new().nest_service("/mcp", service);
453    if let Some(token) = cfg.token.clone() {
454        let expected: Arc<[u8]> = format!("Bearer {token}").into_bytes().into();
455        router = router.layer(axum::middleware::from_fn(
456            move |req: axum::extract::Request, next: axum::middleware::Next| {
457                let expected = expected.clone();
458                async move {
459                    let given = req
460                        .headers()
461                        .get(axum::http::header::AUTHORIZATION)
462                        .map(|v| v.as_bytes())
463                        .unwrap_or_default();
464                    if constant_time_eq(given, &expected) {
465                        next.run(req).await
466                    } else {
467                        axum::response::IntoResponse::into_response((
468                            axum::http::StatusCode::UNAUTHORIZED,
469                            [(axum::http::header::WWW_AUTHENTICATE, "Bearer")],
470                            "missing or wrong bearer token\n",
471                        ))
472                    }
473                }
474            },
475        ));
476    }
477    let listener = tokio::net::TcpListener::bind(addr)
478        .await
479        .map_err(|e| format!("binding {addr}: {e}"))?;
480    let bound = listener.local_addr().map_err(|e| e.to_string())?;
481    describe(&state, &format!("Streamable HTTP on http://{bound}/mcp"));
482    axum::serve(listener, router)
483        .with_graceful_shutdown(async move {
484            shutdown_signal().await;
485            ct.cancel();
486        })
487        .await
488        .map_err(|e| format!("serving {bound}: {e}"))
489}
490
491/// Ctrl-C, or SIGTERM on Unix — what `docker stop` sends, and a process
492/// that is a container's PID 1 ignores a signal it installed no handler for.
493async fn shutdown_signal() {
494    #[cfg(unix)]
495    let terminate = async {
496        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
497            Ok(mut s) => {
498                s.recv().await;
499            }
500            Err(_) => std::future::pending::<()>().await,
501        }
502    };
503    #[cfg(not(unix))]
504    let terminate = std::future::pending::<()>();
505    tokio::select! {
506        _ = tokio::signal::ctrl_c() => {}
507        _ = terminate => {}
508    }
509}
510
511/// Byte comparison whose time does not depend on where the inputs differ —
512/// a token check must not leak its prefix through response timing.
513fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
514    if a.len() != b.len() {
515        return false;
516    }
517    a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
518}
519
520// --- the tools ----------------------------------------------------------------
521
522#[derive(Deserialize, schemars::JsonSchema)]
523struct ConvertToMarkdownArgs {
524    /// The document to read: an http: or https: URL (only when the server
525    /// allows URL fetching — see list_input_formats), a file: URI, a data:
526    /// URI, or a file path. Relative paths resolve against the server's
527    /// root; files outside it are refused.
528    uri: String,
529}
530
531#[derive(Deserialize, schemars::JsonSchema)]
532struct ConvertArgs {
533    /// The document to read: an http: or https: URL (only when the server
534    /// allows URL fetching — see list_input_formats), a file: URI, a data:
535    /// URI, or a file path. Relative paths resolve against the server's
536    /// root; files outside it are refused.
537    uri: String,
538    /// Output format: md (Markdown, the default), json (docling's
539    /// DoclingDocument: structure, tables and page provenance), html, text,
540    /// latex, chunks (RAG-ready chunk records as JSON), vtt (WebVTT, for
541    /// audio/video transcripts) or pandoc (Pandoc's JSON AST).
542    // Optional parameters are single-typed in the schema and left out of
543    // `required` — a `["string", "null"]` type union is what some clients'
544    // function-calling dialects reject (MCP Inspector's portability check);
545    // an explicit `null` still deserializes as "not given".
546    #[serde(default)]
547    #[schemars(transform = drop_null)]
548    to: Option<String>,
549    /// Pictures in md, html or pandoc output: placeholder (the default, an
550    /// `<!-- image -->` marker) or embedded (the image as a data: URI).
551    #[serde(default)]
552    #[schemars(transform = drop_null)]
553    images: Option<String>,
554    /// Conversion options, docling.rs's shared set (docs/OPTIONS.md), e.g.
555    /// {"pages": "1-5"}, {"text_layer_only": true} (digital PDFs, fastest),
556    /// {"ocr_lang": "ch"}, {"force_full_page_ocr": true},
557    /// {"do_picture_ocr": true} (OCR pictures inside Office files),
558    /// {"password": "…"}, {"compact_tables": false}. A value may also be
559    /// given as text ("true", "1.5"), as a form sends it.
560    #[serde(default)]
561    #[schemars(transform = drop_null)]
562    options: Option<serde_json::Map<String, serde_json::Value>>,
563}
564
565/// An `Option<T>` field's schema as `T`'s: `"type": ["T", "null"]` → `"T"`,
566/// and no `"default": null` — absence already says "not given".
567fn drop_null(schema: &mut schemars::Schema) {
568    if let Some(serde_json::Value::Array(types)) = schema.get("type").cloned() {
569        let kept: Vec<_> = types.into_iter().filter(|t| t != "null").collect();
570        if let [single] = kept.as_slice() {
571            schema.insert("type".into(), single.clone());
572        }
573    }
574    if schema.get("default") == Some(&serde_json::Value::Null) {
575        schema.remove("default");
576    }
577}
578
579/// The MCP service: one per stdio connection or HTTP session, sharing the
580/// operator's [`State`].
581#[derive(Clone)]
582struct DoclingMcp {
583    state: Arc<State>,
584    tool_router: ToolRouter<Self>,
585}
586
587impl DoclingMcp {
588    fn new(state: Arc<State>) -> Self {
589        Self {
590            state,
591            tool_router: Self::tool_router(),
592        }
593    }
594
595    /// Convert on the blocking pool under a concurrency permit, sending a
596    /// progress heartbeat while it runs when the caller asked for progress.
597    async fn run_conversion(
598        &self,
599        request: Request,
600        ctx: &RequestContext<RoleServer>,
601    ) -> Result<String, String> {
602        let permit = self
603            .state
604            .permits
605            .clone()
606            .acquire_owned()
607            .await
608            .map_err(|e| e.to_string())?;
609        let state = self.state.clone();
610        // The permit lives as long as the work: a call the client cancels
611        // drops this future, not the conversion already running, and must
612        // not free a slot that conversion still occupies.
613        let mut job = tokio::task::spawn_blocking(move || {
614            let _permit = permit;
615            let result = convert(&state, &request);
616            // What the conversion freed goes back to the OS, not into the
617            // allocator's arenas (`docling::memory`).
618            docling::memory::release_free_memory();
619            result
620        });
621        let token = ctx.meta.get_progress_token();
622        let mut tick = tokio::time::interval(Duration::from_secs(10));
623        tick.tick().await; // the first tick is immediate
624        let mut beats = 0u32;
625        loop {
626            tokio::select! {
627                done = &mut job => {
628                    return done.map_err(|e| format!("conversion worker failed: {e}"))?;
629                }
630                _ = tick.tick(), if token.is_some() => {
631                    beats += 1;
632                    let param = ProgressNotificationParam::new(
633                        token.clone().expect("guarded"),
634                        f64::from(beats),
635                    )
636                    .with_message(format!("converting ({}s)", beats * 10));
637                    let _ = ctx.peer.notify_progress(param).await;
638                }
639            }
640        }
641    }
642}
643
644#[tool_router]
645impl DoclingMcp {
646    /// Read a document as Markdown, with default settings, and return the
647    /// Markdown text. Handles PDF (layout analysis, tables, OCR for scans),
648    /// Word, PowerPoint, Excel, HTML, EPUB, e-mail, images, audio and more.
649    /// Use this whenever Markdown is all you need. Use `convert` instead for
650    /// another output format (docling JSON, HTML, RAG chunks, …), embedded
651    /// images, or options such as a page range, OCR language or password.
652    /// Fails with a message when the document is missing, outside the
653    /// server's root, of an unsupported type (see `list_input_formats`), or
654    /// a URL while URL fetching is off. Read-only. Same name and contract as
655    /// MarkItDown's MCP tool.
656    #[tool(annotations(
657        title = "Convert to Markdown",
658        read_only_hint = true,
659        open_world_hint = true
660    ))]
661    async fn convert_to_markdown(
662        &self,
663        Parameters(args): Parameters<ConvertToMarkdownArgs>,
664        ctx: RequestContext<RoleServer>,
665    ) -> Result<String, String> {
666        let request = Request {
667            uri: args.uri,
668            to: "md".into(),
669            images: ImageMode::Placeholder,
670            options: ConvertOptions::default(),
671        };
672        self.run_conversion(request, &ctx).await
673    }
674
675    /// Convert a document to a chosen output format, with conversion
676    /// options, and return the result as text. `to` picks the format
677    /// (Markdown, docling JSON with structure and page provenance, HTML,
678    /// plain text, LaTeX, RAG chunks, WebVTT, Pandoc JSON); `images` embeds
679    /// pictures instead of placeholders; `options` sets page ranges, OCR
680    /// language and mode, text-layer-only PDFs, passwords and the rest.
681    /// For plain Markdown with default settings, `convert_to_markdown` is
682    /// the simpler call. Inputs and errors as for `convert_to_markdown`;
683    /// an unknown `to`, `images` value or option key is an error that says
684    /// what is accepted. Read-only.
685    #[tool(annotations(
686        title = "Convert to a chosen format",
687        read_only_hint = true,
688        open_world_hint = true
689    ))]
690    async fn convert(
691        &self,
692        Parameters(args): Parameters<ConvertArgs>,
693        ctx: RequestContext<RoleServer>,
694    ) -> Result<String, String> {
695        let request = Request::from_args(args)?;
696        self.run_conversion(request, &ctx).await
697    }
698
699    /// List the file extensions this server can convert, one per line, and
700    /// whether it accepts http(s) URLs. Takes no arguments and converts
701    /// nothing. Call it before `convert_to_markdown` or `convert` when
702    /// unsure whether a file type is supported, or to learn why a URL was
703    /// refused.
704    #[tool(annotations(title = "List input formats", read_only_hint = true))]
705    async fn list_input_formats(&self) -> String {
706        let mut out = InputFormat::supported_extensions().join("\n");
707        out.push_str(if self.state.allow_url_fetch {
708            "\n\nURL inputs (http/https): enabled"
709        } else {
710            "\n\nURL inputs (http/https): disabled (the server was started without --allow-url-fetch)"
711        });
712        out
713    }
714}
715
716#[tool_handler(router = self.tool_router)]
717impl ServerHandler for DoclingMcp {
718    fn get_info(&self) -> ServerConfig {
719        let mut info = Implementation::new("docling-rs", env!("CARGO_PKG_VERSION"));
720        info.title = Some("docling.rs".into());
721        info.website_url = Some("https://github.com/docling-project/docling.rs".into());
722        ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
723            .with_server_info(info)
724            .with_instructions(format!(
725                "Converts documents to Markdown or docling JSON for reading: PDF (layout, \
726                 tables, OCR), DOCX, PPTX, XLSX, HTML, EPUB, e-mail, images, audio and more. \
727                 Tools: convert_to_markdown for Markdown with default settings; convert for \
728                 any other output format or for options (e.g. {{\"pages\": \"1-5\"}}); \
729                 list_input_formats to check what this server accepts. Local files: paths under {}. URLs: {}.",
730                self.state.roots_display(),
731                if self.state.allow_url_fetch {
732                    "enabled"
733                } else {
734                    "disabled on this server"
735                }
736            ))
737    }
738}
739
740// --- the conversion -----------------------------------------------------------
741
742/// One validated tool call.
743struct Request {
744    uri: String,
745    to: String,
746    images: ImageMode,
747    options: ConvertOptions,
748}
749
750/// The `to` values the tools return — every text output of the CLI's
751/// `--to` (`dclx` is a ZIP and `images` page PNGs, neither of which fits a
752/// text result).
753const OUTPUTS: &[&str] = &[
754    "md", "json", "html", "text", "latex", "chunks", "vtt", "pandoc",
755];
756
757impl Request {
758    fn from_args(args: ConvertArgs) -> Result<Self, String> {
759        let to = match args.to.as_deref().map(str::trim) {
760            None | Some("") | Some("md") | Some("markdown") => "md".to_string(),
761            Some(t) if OUTPUTS.contains(&t) => t.to_string(),
762            Some(t) => {
763                return Err(format!(
764                    "unknown to={t:?} (expected one of: {})",
765                    OUTPUTS.join(", ")
766                ))
767            }
768        };
769        let images = match args.images.as_deref().map(str::trim) {
770            None | Some("") | Some("placeholder") => ImageMode::Placeholder,
771            Some("embedded") => ImageMode::Embedded,
772            Some(other) => {
773                return Err(format!(
774                    "unknown images={other:?} (expected: placeholder, embedded)"
775                ))
776            }
777        };
778        let options = match args.options {
779            None => ConvertOptions::default(),
780            Some(map) => {
781                let unknown = ConvertOptions::unknown_keys(map.keys().map(String::as_str), &[]);
782                if let Some(key) = unknown.first() {
783                    return Err(format!(
784                        "options: unknown field `{key}` (see docs/OPTIONS.md for the list)"
785                    ));
786                }
787                // Values as text too — MCP Inspector's form sends every
788                // value as a string: `{"force_full_page_ocr": "true"}`.
789                ConvertOptions::from_loose_json(map).map_err(|e| format!("options: {e}"))?
790            }
791        };
792        Ok(Self {
793            uri: args.uri,
794            to,
795            images,
796            options,
797        })
798    }
799}
800
801/// Resolve, convert and render one request — the blocking half of a tool
802/// call.
803fn convert(state: &State, request: &Request) -> Result<String, String> {
804    let source = resolve_source(state, &request.uri)?;
805    let mut options = guard_options(state, &request.options)?;
806    // Markdown for a model to read: unpadded `| a | b |` tables carry the
807    // same cells in far fewer tokens (the MarkItDown facade's choice too);
808    // the caller's explicit `compact_tables` wins.
809    if request.to == "md" && options.compact_tables.is_none() {
810        options.compact_tables = Some(true);
811    }
812    let document = convert_document(state, &source, &options)?;
813    render(&document, &request.to, request.images)
814}
815
816fn convert_document(
817    state: &State,
818    source: &SourceDocument,
819    options: &ConvertOptions,
820) -> Result<docling::DoclingDocument, String> {
821    let converter = options
822        .apply(DocumentConverter::new().warm_pipeline(&state.warm))
823        .map_err(|e| e.to_string())?;
824    // The remote VLM pipeline (#304) is a sibling path, as in docling-serve.
825    if let Some(vlm) = options.vlm_options().map_err(|e| e.to_string())? {
826        let mut document = docling::vlm::convert_vlm(source, &vlm).map_err(|e| e.to_string())?;
827        converter.finish_document(&mut document);
828        return Ok(document);
829    }
830    match converter.convert(source.clone()) {
831        Ok(result) => Ok(result.document),
832        // No layout model on this machine (the release binaries ship none):
833        // a digital PDF still has its text layer, which is what MarkItDown
834        // reads — convert that rather than fail, and say once how to get the
835        // full pipeline. An explicit `text_layer_only` is the caller's call.
836        Err(e)
837            if source.format == InputFormat::Pdf
838                && options.text_layer_only.is_none()
839                && e.to_string().contains("model not found") =>
840        {
841            if !state.warned_text_layer.swap(true, Ordering::Relaxed) {
842                eprintln!(
843                    "{}: the layout models are missing, so PDFs convert from their text \
844                     layer (no layout analysis, table structure or OCR). {}",
845                    state.command, state.models_hint
846                );
847            }
848            // A converter of its own: the text-layer pipeline loads no
849            // models, and putting it in the warm slot would only evict them.
850            let retry = DocumentConverter::new().text_layer_only(true);
851            let converter = options.apply(retry).map_err(|e| e.to_string())?;
852            converter
853                .convert(source.clone())
854                .map(|r| r.document)
855                .map_err(|e| e.to_string())
856        }
857        Err(e) => Err(e.to_string()),
858    }
859}
860
861fn render(
862    document: &docling::DoclingDocument,
863    to: &str,
864    images: ImageMode,
865) -> Result<String, String> {
866    Ok(match to {
867        "md" => match images {
868            ImageMode::Placeholder => document.export_to_markdown(),
869            mode => document.export_to_markdown_with_images(mode, "artifacts").0,
870        },
871        "json" => document.export_to_json(),
872        "html" => document.export_to_html(),
873        "text" => document.export_to_text(),
874        "latex" => document.export_to_latex(),
875        "vtt" => document.export_to_vtt(),
876        "chunks" => {
877            let mut warn = |msg: String| eprintln!("warning: {msg}");
878            let records = docling::chunks::chunk_records(document, &mut warn);
879            serde_json::to_string_pretty(&records).map_err(|e| e.to_string())?
880        }
881        "pandoc" => {
882            document
883                .export_to_pandoc_json_with(&docling::pandoc::PandocExportOptions {
884                    image_mode: images,
885                    ..Default::default()
886                })
887                .map_err(|e| e.to_string())?
888                .0
889        }
890        other => return Err(format!("unknown to={other:?}")),
891    })
892}
893
894/// The caller's options under the operator's policy — docling-serve's rules
895/// for everything that leaves the machine, the root for everything that
896/// names a file.
897fn guard_options(state: &State, options: &ConvertOptions) -> Result<ConvertOptions, String> {
898    let mut o = options.clone();
899    o.validate().map_err(|e| e.to_string())?;
900    // Remote `<img src>` is an outbound fetch like a URL input: without the
901    // flag the call gets the safe tier (`data:` URIs and container parts)
902    // instead of a surprise request — docling-serve's behavior.
903    let requested = o.image_sources().map_err(|e| e.to_string())?.or_else(|| {
904        o.fetch_images
905            .filter(|&f| f)
906            .map(|_| docling::ImageSources::Remote)
907    });
908    if requested == Some(docling::ImageSources::Remote) && !state.allow_url_fetch {
909        o.image_sources = Some(docling::ImageSources::Embedded.to_string());
910        o.fetch_images = Some(false);
911    }
912    if let Some(endpoint) = o.vlm_endpoint.as_deref().filter(|v| !v.trim().is_empty()) {
913        if !state.allow_url_fetch {
914            return Err(
915                "a request-supplied vlm_endpoint needs the server started with \
916                 --allow-url-fetch (or pin it with DOCLING_RS_VLM_ENDPOINT)"
917                    .into(),
918            );
919        }
920        docling::fetch::check_outbound_url(endpoint, false)?;
921    }
922    if o.use_web_browser == Some(true) && !state.allow_url_fetch {
923        return Err(
924            "use_web_browser loads the page's remote resources; it needs the server \
925             started with --allow-url-fetch"
926                .into(),
927        );
928    }
929    if let Some(dir) = o.xbrl_taxonomy.as_deref() {
930        o.xbrl_taxonomy = Some(local_path(state, Path::new(dir))?.display().to_string());
931    }
932    // Inline copybook JSON is data; anything else names a file.
933    if let Some(layout) = o.ebcdic_layout.as_deref() {
934        if !layout.trim_start().starts_with('{') {
935            o.ebcdic_layout = Some(local_path(state, Path::new(layout))?.display().to_string());
936        }
937    }
938    // A preset is a directory name under `.models/asr/`, never a path.
939    if let Some(model) = o.asr_model.as_deref() {
940        if model.contains(['/', '\\']) || model.contains("..") {
941            return Err(format!("asr_model must be a preset name, got {model:?}"));
942        }
943    }
944    Ok(o)
945}
946
947/// The document a `uri` names: a `data:` URI, an `http(s)` URL (with
948/// `--allow-url-fetch`), a `file:` URI or a path under the root.
949fn resolve_source(state: &State, uri: &str) -> Result<SourceDocument, String> {
950    let uri = uri.trim();
951    if uri.is_empty() {
952        return Err("uri is empty".into());
953    }
954    let lower = uri.get(..8).unwrap_or(uri).to_ascii_lowercase();
955    if lower.starts_with("data:") {
956        return docling::fetch::from_data_url(uri).map_err(|e| e.to_string());
957    }
958    if lower.starts_with("http://") || lower.starts_with("https://") {
959        if !state.allow_url_fetch {
960            return Err(format!(
961                "fetching URLs is disabled on this server (it was started without \
962                 --allow-url-fetch); pass a local path or file: URI under {} instead",
963                state.roots_display()
964            ));
965        }
966        return SourceDocument::from_url(uri, &state.fetch_policy).map_err(|e| e.to_string());
967    }
968    let path = if lower.starts_with("file:") {
969        docling::fetch::file_url_path(uri)?
970    } else if let Some(scheme) = uri_scheme(uri) {
971        return Err(format!(
972            "unsupported URI scheme {scheme:?} (expected http, https, file, data, or a path)"
973        ));
974    } else {
975        PathBuf::from(uri)
976    };
977    let path = local_path(state, &path)?;
978    if path.is_dir() {
979        return Err(format!("{} is a directory, not a document", path.display()));
980    }
981    match SourceDocument::from_file(&path) {
982        Ok(source) => Ok(source),
983        // No (known) extension: read it and let the content decide.
984        Err(_) => {
985            let bytes = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
986            let name = path
987                .file_name()
988                .and_then(|n| n.to_str())
989                .unwrap_or("document");
990            let mut source = SourceDocument::from_named_bytes(name, bytes, None)
991                .map_err(|e| format!("{}: {e}", path.display()))?;
992            source.path = Some(path);
993            Ok(source)
994        }
995    }
996}
997
998/// The server's URL-fetch policy on top of the library's bounds
999/// (`DOCLING_RS_MAX_FETCH_BYTES`, 10 s connect / 300 s total): up to five
1000/// redirects, each hop re-checked against the private-address block —
1001/// links agents are handed (`http:` → `https:`, an arXiv abstract → its
1002/// PDF) redirect routinely, and the per-hop check keeps a public URL from
1003/// bouncing onto an internal one. docling-serve refuses redirects instead.
1004fn fetch_policy() -> docling::FetchPolicy {
1005    docling::FetchPolicy {
1006        max_redirects: 5,
1007        ..docling::FetchPolicy::default()
1008    }
1009}
1010
1011/// `scheme` of `scheme:rest` when `uri` has one — a URI scheme is two or
1012/// more characters, so a Windows drive (`C:\docs\a.pdf`) is a path.
1013fn uri_scheme(uri: &str) -> Option<&str> {
1014    let (scheme, _) = uri.split_once(':')?;
1015    let valid = scheme.len() >= 2
1016        && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
1017        && scheme
1018            .chars()
1019            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
1020    valid.then_some(scheme)
1021}
1022
1023/// `path` resolved against the first root and confined to the roots: the
1024/// lexically normalized path must lie under one (so nothing outside is
1025/// touched — not even to learn whether it exists), and so must the
1026/// canonical one (a symlink inside a root cannot lead out of it). The
1027/// lexical check takes a root in either spelling, so `/tmp/docs/a.pdf`
1028/// passes under a `/tmp/docs` root whose canonical form is
1029/// `/private/tmp/docs`.
1030fn local_path(state: &State, path: &Path) -> Result<PathBuf, String> {
1031    let joined = if path.is_absolute() {
1032        path.to_path_buf()
1033    } else {
1034        state.roots[0].canonical.join(path)
1035    };
1036    let outside = || {
1037        format!(
1038            "{} is outside the server's root ({}); start the server with --root to allow it",
1039            path.display(),
1040            state.roots_display()
1041        )
1042    };
1043    let lexical = normalize(&joined);
1044    let under = |p: &Path| {
1045        state
1046            .roots
1047            .iter()
1048            .any(|r| p.starts_with(&r.given) || p.starts_with(&r.canonical))
1049    };
1050    if !under(&lexical) {
1051        return Err(outside());
1052    }
1053    let canonical = std::fs::canonicalize(&lexical)
1054        .map_err(|e| format!("cannot open {}: {e}", path.display()))?;
1055    if !state
1056        .roots
1057        .iter()
1058        .any(|r| canonical.starts_with(&r.canonical))
1059    {
1060        return Err(outside());
1061    }
1062    Ok(canonical)
1063}
1064
1065/// `.` and `..` folded away without touching the file system.
1066fn normalize(path: &Path) -> PathBuf {
1067    let mut out = PathBuf::new();
1068    for component in path.components() {
1069        match component {
1070            Component::ParentDir => {
1071                out.pop();
1072            }
1073            Component::CurDir => {}
1074            other => out.push(other),
1075        }
1076    }
1077    out
1078}
1079
1080/// A `data:[<mime>][;charset=…][;base64],<payload>` URI as a document: the
1081/// format from the media type, else the content's signature; a `charset`
1082/// decodes text formats.
1083#[cfg(test)]
1084mod tests {
1085    use super::*;
1086
1087    fn state(root: &Path, allow_url_fetch: bool) -> State {
1088        State {
1089            roots: vec![Root::new(root.to_str().unwrap()).unwrap()],
1090            allow_url_fetch,
1091            fetch_policy: fetch_policy(),
1092            permits: Arc::new(tokio::sync::Semaphore::new(1)),
1093            warned_text_layer: AtomicBool::new(false),
1094            command: Launcher::CLI.command.to_string(),
1095            models_hint: Launcher::CLI.models_hint.to_string(),
1096            warm: docling::WarmPipeline::new(),
1097        }
1098    }
1099
1100    fn fixtures() -> PathBuf {
1101        Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/data")
1102    }
1103
1104    #[test]
1105    fn paths_stay_under_the_root() {
1106        let root = fixtures().join("md");
1107        let s = state(&root, false);
1108        // Relative paths resolve against the root.
1109        let ok = local_path(&s, Path::new("sources")).unwrap();
1110        assert!(ok.ends_with("md/sources"));
1111        // `..` out of the root is refused before the file system is asked.
1112        for escape in [
1113            "../docx/sources",
1114            "sources/../../docx",
1115            "/etc/passwd",
1116            "/nonexistent/x.pdf",
1117        ] {
1118            let err = local_path(&s, Path::new(escape)).unwrap_err();
1119            assert!(err.contains("outside the server's root"), "{escape}: {err}");
1120        }
1121    }
1122
1123    /// A root reached through a symlink (macOS's `/tmp` → `/private/tmp`)
1124    /// accepts absolute paths in the spelling the operator gave.
1125    #[cfg(unix)]
1126    #[test]
1127    fn a_root_behind_a_symlink_takes_both_spellings() {
1128        let dir = std::env::temp_dir().join(format!("docling-mcp-link-{}", std::process::id()));
1129        let _ = std::fs::remove_dir_all(&dir);
1130        std::fs::create_dir_all(&dir).unwrap();
1131        let link = dir.join("docs");
1132        std::os::unix::fs::symlink(fixtures().join("md"), &link).unwrap();
1133        let s = state(&link, false);
1134        let via_link = link.join("sources");
1135        assert!(local_path(&s, &via_link).is_ok());
1136        let via_target = fixtures().join("md/sources");
1137        assert!(local_path(&s, &std::fs::canonicalize(via_target).unwrap()).is_ok());
1138        assert!(local_path(&s, &dir.join("docs/../elsewhere")).is_err());
1139        std::fs::remove_dir_all(&dir).unwrap();
1140    }
1141
1142    #[cfg(unix)]
1143    #[test]
1144    fn a_symlink_cannot_lead_out_of_the_root() {
1145        let dir = std::env::temp_dir().join(format!("docling-mcp-{}", std::process::id()));
1146        let _ = std::fs::remove_dir_all(&dir);
1147        std::fs::create_dir_all(&dir).unwrap();
1148        std::os::unix::fs::symlink(fixtures().join("docx"), dir.join("out")).unwrap();
1149        let s = state(&dir, false);
1150        let err = local_path(&s, Path::new("out/sources")).unwrap_err();
1151        assert!(err.contains("outside the server's root"), "{err}");
1152        std::fs::remove_dir_all(&dir).unwrap();
1153    }
1154
1155    #[test]
1156    fn uri_kinds() {
1157        assert_eq!(uri_scheme("s3://bucket/x.pdf"), Some("s3"));
1158        assert_eq!(uri_scheme("ftp://h/x"), Some("ftp"));
1159        assert_eq!(uri_scheme("C:\\docs\\a.pdf"), None);
1160        assert_eq!(uri_scheme("report.pdf"), None);
1161        let s = state(&fixtures(), false);
1162        let err = resolve_source(&s, "ftp://example.com/a.pdf").unwrap_err();
1163        assert!(err.contains("unsupported URI scheme"), "{err}");
1164        let err = resolve_source(&s, "https://example.com/a.pdf").unwrap_err();
1165        assert!(err.contains("--allow-url-fetch"), "{err}");
1166        let err = resolve_source(&s, "docx").unwrap_err();
1167        assert!(err.contains("is a directory"), "{err}");
1168    }
1169
1170    /// `data:` URIs decode in the library (`docling::fetch::from_data_url`)
1171    /// whether or not URL fetching is on — nothing leaves the machine.
1172    #[test]
1173    fn data_uris_decode() {
1174        let s = state(&fixtures(), false);
1175        let src = resolve_source(&s, "data:text/markdown;base64,IyBUaXRsZQoKSGVsbG8=").unwrap();
1176        assert_eq!(src.format, InputFormat::Md);
1177        assert_eq!(src.bytes, b"# Title\n\nHello");
1178        let src = resolve_source(&s, "DATA:text/html,%3Ch1%3EHi%3C/h1%3E").unwrap();
1179        assert_eq!(src.format, InputFormat::Html);
1180        assert_eq!(src.bytes, b"<h1>Hi</h1>");
1181        // No media type: the signature decides.
1182        let src = resolve_source(&s, "data:;base64,JVBERi0xLjQK").unwrap();
1183        assert_eq!(src.format, InputFormat::Pdf);
1184        let src = resolve_source(&s, "data:text/csv;charset=shift_jis,a,b").unwrap();
1185        assert_eq!(src.encoding.as_deref(), Some("shift_jis"));
1186        assert!(resolve_source(&s, "data:text/plain").is_err());
1187        // Untyped text is plain text since #671; untyped binary is refused.
1188        let src = resolve_source(&s, "data:application/octet-stream,xyz").unwrap();
1189        assert_eq!(src.format, InputFormat::Text);
1190        assert!(resolve_source(&s, "data:application/octet-stream;base64,AAECAwQF").is_err());
1191    }
1192
1193    #[test]
1194    fn options_follow_the_operator_policy() {
1195        let s = state(&fixtures(), false);
1196        let opts: ConvertOptions =
1197            serde_json::from_value(serde_json::json!({"image_sources": "remote"})).unwrap();
1198        let guarded = guard_options(&s, &opts).unwrap();
1199        assert_eq!(guarded.image_sources.as_deref(), Some("embedded"));
1200        let opts: ConvertOptions =
1201            serde_json::from_value(serde_json::json!({"vlm_endpoint": "http://h/v1"})).unwrap();
1202        assert!(guard_options(&s, &opts)
1203            .unwrap_err()
1204            .contains("--allow-url-fetch"));
1205        let opts: ConvertOptions =
1206            serde_json::from_value(serde_json::json!({"xbrl_taxonomy": "/etc"})).unwrap();
1207        assert!(guard_options(&s, &opts).unwrap_err().contains("outside"));
1208        let opts: ConvertOptions =
1209            serde_json::from_value(serde_json::json!({"asr_model": "../../x"})).unwrap();
1210        assert!(guard_options(&s, &opts)
1211            .unwrap_err()
1212            .contains("preset name"));
1213        // With the flag, remote images stay remote.
1214        let s = state(&fixtures(), true);
1215        let opts: ConvertOptions =
1216            serde_json::from_value(serde_json::json!({"fetch_images": true})).unwrap();
1217        let guarded = guard_options(&s, &opts).unwrap();
1218        assert_ne!(guarded.image_sources.as_deref(), Some("embedded"));
1219    }
1220
1221    #[test]
1222    fn requests_validate_their_arguments() {
1223        let args = |v: serde_json::Value| serde_json::from_value::<ConvertArgs>(v).unwrap();
1224        let r = Request::from_args(args(serde_json::json!({"uri": "a.docx"}))).unwrap();
1225        assert_eq!(r.to, "md");
1226        let err = Request::from_args(args(serde_json::json!({"uri": "a", "to": "dclx"})))
1227            .map(|_| ())
1228            .unwrap_err();
1229        assert!(err.contains("unknown to"), "{err}");
1230        let err = Request::from_args(args(
1231            serde_json::json!({"uri": "a", "options": {"text_layer_onyl": true}}),
1232        ))
1233        .map(|_| ())
1234        .unwrap_err();
1235        assert!(err.contains("unknown field `text_layer_onyl`"), "{err}");
1236        let r = Request::from_args(args(
1237            serde_json::json!({"uri": "a", "to": "json", "options": {"pages": "1-2"}}),
1238        ))
1239        .unwrap();
1240        assert_eq!(r.options.pages.as_deref(), Some("1-2"));
1241        // A form's text values read as the option's type.
1242        let r = Request::from_args(args(serde_json::json!({
1243            "uri": "a",
1244            "options": {"force_full_page_ocr": "true", "ocr_scale": "1.5", "pages": "3", "video_frames": 2}
1245        })))
1246        .unwrap();
1247        assert_eq!(r.options.force_full_page_ocr, Some(true));
1248        assert_eq!(r.options.ocr_scale, Some(1.5));
1249        assert_eq!(r.options.pages.as_deref(), Some("3"));
1250        assert_eq!(r.options.video_frames, Some(2));
1251        let err = Request::from_args(args(
1252            serde_json::json!({"uri": "a", "options": {"force_full_page_ocr": "maybe"}}),
1253        ))
1254        .map(|_| ())
1255        .unwrap_err();
1256        assert!(
1257            err.contains("force_full_page_ocr: cannot read \"maybe\""),
1258            "{err}"
1259        );
1260    }
1261
1262    #[test]
1263    fn converts_a_docx_to_compact_markdown() {
1264        let s = state(&fixtures(), false);
1265        let request = Request {
1266            uri: "docx/sources/lorem_ipsum.docx".into(),
1267            to: "md".into(),
1268            images: ImageMode::Placeholder,
1269            options: ConvertOptions::default(),
1270        };
1271        let md = convert(&s, &request).unwrap();
1272        assert!(md.contains("Lorem ipsum"), "{md}");
1273    }
1274
1275    /// Calls share the server's warm pipeline (#669) without sharing their
1276    /// options: a page window on one call does not cut the next.
1277    #[test]
1278    fn calls_on_the_warm_pipeline_keep_their_own_options() {
1279        let warm = state(&fixtures(), false);
1280        let request = |pages: Option<&str>| Request {
1281            uri: "pdf/sources/2206.01062.pdf".into(),
1282            to: "json".into(),
1283            images: ImageMode::Placeholder,
1284            options: ConvertOptions {
1285                text_layer_only: Some(true),
1286                pages: pages.map(str::to_string),
1287                ..Default::default()
1288            },
1289        };
1290        for pages in [Some("2-3"), None, Some("1-1"), None] {
1291            let cold = convert(&state(&fixtures(), false), &request(pages)).unwrap();
1292            assert_eq!(
1293                convert(&warm, &request(pages)).unwrap(),
1294                cold,
1295                "pages {pages:?}"
1296            );
1297        }
1298    }
1299
1300    /// `--flag=value` reads like `--flag value`; switches take true/false.
1301    #[test]
1302    fn flags_accept_the_equals_spelling() {
1303        let v = |a: &[&str]| split_flag_values(a.iter().map(|s| s.to_string()).collect());
1304        assert_eq!(
1305            v(&[
1306                "--root=/a",
1307                "--allow-url-fetch=true",
1308                "--http=false",
1309                "--port=9"
1310            ])
1311            .unwrap(),
1312            ["--root", "/a", "--allow-url-fetch", "--port", "9"]
1313        );
1314        assert_eq!(v(&["--root", "/a=b"]).unwrap(), ["--root", "/a=b"]);
1315        assert!(v(&["--allow-url-fetch=maybe"]).is_err());
1316    }
1317
1318    /// Optional parameters are single-typed and not required (MCP
1319    /// Inspector's portability check: no `["string", "null"]` unions).
1320    #[test]
1321    fn tool_schemas_are_portable() {
1322        let schema = serde_json::to_value(schemars::schema_for!(ConvertArgs)).unwrap();
1323        assert_eq!(schema["required"], serde_json::json!(["uri"]));
1324        for (name, ty) in [
1325            ("to", "string"),
1326            ("images", "string"),
1327            ("options", "object"),
1328        ] {
1329            let prop = &schema["properties"][name];
1330            assert_eq!(prop["type"], ty, "{name}: {prop}");
1331            assert!(prop.get("default").is_none(), "{name}: {prop}");
1332        }
1333        // An explicit null is still "not given".
1334        let args: ConvertArgs = serde_json::from_value(
1335            serde_json::json!({"uri": "a.md", "to": null, "images": null, "options": null}),
1336        )
1337        .unwrap();
1338        assert_eq!(Request::from_args(args).unwrap().to, "md");
1339    }
1340
1341    #[test]
1342    fn bearer_comparison() {
1343        assert!(constant_time_eq(b"Bearer abc", b"Bearer abc"));
1344        assert!(!constant_time_eq(b"Bearer abd", b"Bearer abc"));
1345        assert!(!constant_time_eq(b"Bearer ab", b"Bearer abc"));
1346        assert!(!constant_time_eq(b"", b"Bearer abc"));
1347    }
1348}