ocr-mcp 0.1.0

MCP server that transcribes screenshots with a local GLM-OCR model via llama-server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
// Copyright (c) 2026 Enzo Lombardi
// SPDX-License-Identifier: MIT

//! Owning the `llama-server` child process.
//!
//! Argument-vector construction, binary lookup and port selection are pure and
//! tested directly; spawning is exercised separately with a fake binary. The
//! child's stdout and stderr are always piped, never inherited: this process
//! speaks JSON-RPC on stdout, and an inherited child's startup banner would
//! corrupt the framing and wedge the host.

#![allow(
    clippy::duration_suboptimal_units,
    reason = "alternatives (from_mins/from_hours) require Rust 1.91; this crate maintains a lower MSRV"
)]

use crate::config::Config;
use crate::ocr::OcrError;
use std::collections::VecDeque;
use std::io::{BufRead, BufReader, Read};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// How long to wait for `/health` before giving up on a freshly spawned child.
const READY_TIMEOUT: Duration = Duration::from_secs(120);
/// Gap between `/health` polls.
const POLL_INTERVAL: Duration = Duration::from_millis(250);
/// Timeout for a single `/health` liveness probe: it must never let one slow
/// call push a poll iteration past `READY_TIMEOUT`.
const HEALTH_PROBE_TIMEOUT: Duration = Duration::from_secs(2);
/// How many of the most recent lines of child output to retain for error
/// messages.
const TAIL_CAPACITY: usize = 40;

/// A bounded, thread-safe tail of the most recent lines written by the
/// child's stdout/stderr, used only to enrich error text.
#[derive(Clone, Default)]
struct OutputTail(Arc<Mutex<VecDeque<String>>>);

impl OutputTail {
    fn push(&self, line: String) {
        let mut lines = self
            .0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if lines.len() >= TAIL_CAPACITY {
            lines.pop_front();
        }
        lines.push_back(line);
    }

    /// Renders the retained lines, oldest first, joined by newlines.
    fn snapshot(&self) -> String {
        let lines = self
            .0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        lines.iter().cloned().collect::<Vec<_>>().join("\n")
    }

    /// Drains `reader` line by line into this tail until EOF. Runs on its
    /// own thread so the child's pipes never fill and deadlock the process.
    fn drain(self, reader: impl Read) {
        let mut reader = BufReader::new(reader);
        let mut line = String::new();
        loop {
            line.clear();
            match reader.read_line(&mut line) {
                Ok(0) | Err(_) => break,
                Ok(_) => {
                    let trimmed = line.trim_end_matches(['\n', '\r']);
                    self.push(trimmed.to_string());
                }
            }
        }
    }
}

/// Context window to allocate. One image is roughly 2700 tokens and the reply
/// is capped well below `max_tokens`, so this is generous — but it must be set
/// explicitly, because llama-server otherwise allocates KV for the model's
/// full 131072-token context. See `build_argv`.
const CTX_SIZE: u32 = 12000;

/// Builds the `llama-server` argument vector.
///
/// `--flash-attn off` is mandatory: GLM-OCR does not currently work with
/// flash attention enabled. `--no-warmup` keeps first-spawn latency down,
/// since the very next thing that happens is a real request.
///
/// `--ctx-size` and `--parallel` exist to bound memory, and they matter more
/// than they look. Left to its defaults llama-server reserves KV for the full
/// 131072-token context across four parallel slots: 9.78 GB resident for a
/// 1.4 GB model, held for the entire idle window after every call. This server
/// is a guest — it typically shares a machine with the far larger model that
/// called it — and reclaiming that memory when idle is the whole reason it
/// runs as a separate process. Bounding both measured 2.06 GB with identical
/// transcriptions and unchanged latency. We serve one request at a time, so
/// the extra slots buy nothing.
#[must_use]
pub fn build_argv(cfg: &Config, port: u16) -> Vec<String> {
    vec![
        "--model".into(),
        cfg.model.display().to_string(),
        "--mmproj".into(),
        cfg.mmproj.display().to_string(),
        "--port".into(),
        port.to_string(),
        "--host".into(),
        "127.0.0.1".into(),
        "--ctx-size".into(),
        CTX_SIZE.to_string(),
        "--parallel".into(),
        "1".into(),
        "--no-warmup".into(),
        "--flash-attn".into(),
        "off".into(),
    ]
}

/// Resolves the `llama-server` binary: the configured path first, then `PATH`.
///
/// `exists` is injected so the search is testable without touching the
/// filesystem.
///
/// # Errors
/// Returns [`OcrError::BinaryMissing`] when neither lookup finds a file.
pub fn find_binary(
    cfg: &Config,
    path_var: Option<&str>,
    exists: &dyn Fn(&Path) -> bool,
) -> Result<PathBuf, OcrError> {
    if let Some(explicit) = &cfg.binary {
        return if exists(explicit) {
            Ok(explicit.clone())
        } else {
            Err(OcrError::BinaryMissing)
        };
    }
    path_var
        .unwrap_or_default()
        .split(':')
        .filter(|d| !d.is_empty())
        .map(|d| Path::new(d).join("llama-server"))
        .find(|c| exists(c))
        .ok_or(OcrError::BinaryMissing)
}

/// Asks the OS for a free localhost port by binding and immediately dropping.
///
/// # Errors
/// Returns [`OcrError::SpawnFailed`] when no port can be bound.
pub fn free_port() -> Result<u16, OcrError> {
    let listener = std::net::TcpListener::bind("127.0.0.1:0")
        .map_err(|e| OcrError::SpawnFailed(format!("could not reserve a port: {e}")))?;
    listener
        .local_addr()
        .map(|a| a.port())
        .map_err(|e| OcrError::SpawnFailed(format!("could not read the reserved port: {e}")))
}

/// A running `llama-server`, killed on `Drop` so no orphan outlives us.
pub struct Child {
    proc: std::process::Child,
    port: u16,
    last_used: Instant,
    idle: Duration,
    tail: OutputTail,
    /// Set for the duration of an in-flight request so the idle reaper never
    /// drops a child a request is actively using.
    busy: bool,
}

impl Child {
    /// Spawns `llama-server` and waits until `/health` answers.
    ///
    /// # Errors
    /// [`OcrError::WeightsMissing`] when the GGUFs are absent,
    /// [`OcrError::BinaryMissing`] when the binary cannot be found,
    /// [`OcrError::SpawnFailed`] when the process will not start, and
    /// [`OcrError::NotReady`] when `/health` never answers in time.
    pub fn spawn(cfg: &Config) -> Result<Self, OcrError> {
        if !cfg.model.exists() || !cfg.mmproj.exists() {
            return Err(OcrError::WeightsMissing {
                model: cfg.model.clone(),
                mmproj: cfg.mmproj.clone(),
                auto_download: cfg.auto_download,
            });
        }
        let path_var = std::env::var("PATH").ok();
        let bin = find_binary(cfg, path_var.as_deref(), &|p| p.exists())?;
        let port = free_port()?;

        let mut proc = Command::new(&bin)
            .args(build_argv(cfg, port))
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .map_err(|e| OcrError::SpawnFailed(format!("{}: {e}", bin.display())))?;

        let tail = OutputTail::default();
        if let Some(stdout) = proc.stdout.take() {
            let tail = tail.clone();
            std::thread::spawn(move || tail.drain(stdout));
        }
        if let Some(stderr) = proc.stderr.take() {
            let tail = tail.clone();
            std::thread::spawn(move || tail.drain(stderr));
        }

        let mut child = Self {
            proc,
            port,
            last_used: Instant::now(),
            idle: Duration::from_secs(cfg.idle_secs),
            tail,
            busy: false,
        };
        child.await_ready()?;
        Ok(child)
    }

    /// Polls `/health` until it answers or the timeout expires.
    fn await_ready(&mut self) -> Result<(), OcrError> {
        let url = format!("{}/health", self.base_url());
        let deadline = Instant::now() + READY_TIMEOUT;
        while Instant::now() < deadline {
            if let Some(status) = self.proc.try_wait().ok().flatten() {
                return Err(OcrError::NotReady(format!(
                    "the process exited early with {status}\n{}",
                    self.tail.snapshot()
                )));
            }
            if ureq::get(&url)
                .config()
                .timeout_global(Some(HEALTH_PROBE_TIMEOUT))
                .build()
                .call()
                .is_ok()
            {
                return Ok(());
            }
            std::thread::sleep(POLL_INTERVAL);
        }
        Err(OcrError::NotReady(format!(
            "no answer from {url} after {}s\n{}",
            READY_TIMEOUT.as_secs(),
            self.tail.snapshot()
        )))
    }

    /// The `http://127.0.0.1:<port>` root this child serves.
    #[must_use]
    pub fn base_url(&self) -> String {
        format!("http://127.0.0.1:{}", self.port)
    }

    /// Records that the child was just used, restarting the idle countdown.
    pub fn touch(&mut self) {
        self.last_used = Instant::now();
    }

    /// True when the child has gone unused for longer than the idle timeout.
    #[must_use]
    pub fn idle_expired(&self, now: Instant) -> bool {
        expired(self.last_used, self.idle, now)
    }

    /// Marks the child as actively serving (or having finished) a request.
    /// While `true`, [`Child::should_reap`] always returns `false`: a request
    /// in flight must never have its child dropped out from under it.
    pub fn set_busy(&mut self, busy: bool) {
        self.busy = busy;
    }

    /// True when this child is safe to drop: idle-expired and not currently
    /// serving a request.
    #[must_use]
    pub fn should_reap(&self, now: Instant) -> bool {
        should_reap(self.busy, self.last_used, self.idle, now)
    }
}

/// The idle-expiry rule: has `idle` elapsed since `last_used`, as of `now`?
/// Pulled out of [`Child::idle_expired`] so it can be exercised without a
/// process.
fn expired(last_used: Instant, idle: Duration, now: Instant) -> bool {
    now.duration_since(last_used) >= idle
}

/// The full reaping decision: idle-expired *and* not mid-request. Pulled out
/// of [`Child::should_reap`] so the reaper/request race can be exercised
/// without a process.
fn should_reap(busy: bool, last_used: Instant, idle: Duration, now: Instant) -> bool {
    !busy && expired(last_used, idle, now)
}

impl Drop for Child {
    fn drop(&mut self) {
        let _ = self.proc.kill();
        let _ = self.proc.wait();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cfg() -> Config {
        Config {
            model: PathBuf::from("/w/glm-ocr.gguf"),
            mmproj: PathBuf::from("/w/glm-ocr-mmproj.gguf"),
            binary: None,
            idle_secs: 300,
            max_tokens: 1024,
            auto_download: false,
        }
    }

    /// GLM-OCR does not work under llama-server with flash attention on. This
    /// assertion is the whole reason the argv is a pure function.
    #[test]
    fn argv_disables_flash_attention() {
        let argv = build_argv(&cfg(), 8123);
        let joined = argv.join(" ");
        assert!(joined.contains("--flash-attn off"), "got: {joined}");
    }

    #[test]
    fn argv_names_model_projector_and_port() {
        let argv = build_argv(&cfg(), 8123);
        let pair = |flag: &str| {
            argv.iter()
                .position(|a| a == flag)
                .map(|i| argv[i + 1].clone())
        };
        assert_eq!(pair("--model").as_deref(), Some("/w/glm-ocr.gguf"));
        assert_eq!(pair("--mmproj").as_deref(), Some("/w/glm-ocr-mmproj.gguf"));
        assert_eq!(pair("--port").as_deref(), Some("8123"));
        assert!(argv.iter().any(|a| a == "--no-warmup"));
    }

    /// The context and slot count must be bounded explicitly. Left to its
    /// defaults, llama-server allocates KV for the model's full 131072-token
    /// context across 4 parallel slots — measured at 9.78 GB resident for a
    /// 1.4 GB model, held for the whole idle window. On a machine also hosting
    /// an 81 GB ds4, that eviction is what drags the host model into swap.
    /// Bounding it measured 2.06 GB with identical output and latency.
    #[test]
    fn argv_bounds_context_and_slots() {
        let argv = build_argv(&cfg(), 8123);
        let pair = |flag: &str| {
            argv.iter()
                .position(|a| a == flag)
                .map(|i| argv[i + 1].clone())
        };
        assert_eq!(pair("--ctx-size").as_deref(), Some("12000"));
        assert_eq!(pair("--parallel").as_deref(), Some("1"));
    }

    #[test]
    fn configured_binary_wins_over_path() {
        let mut c = cfg();
        c.binary = Some(PathBuf::from("/opt/llama-server"));
        let found = find_binary(&c, Some("/usr/bin:/bin"), &|p| {
            p == Path::new("/opt/llama-server")
        });
        assert_eq!(found.unwrap(), PathBuf::from("/opt/llama-server"));
    }

    #[test]
    fn path_is_searched_when_no_binary_configured() {
        let found = find_binary(&cfg(), Some("/usr/bin:/opt/bin"), &|p| {
            p == Path::new("/opt/bin/llama-server")
        });
        assert_eq!(found.unwrap(), PathBuf::from("/opt/bin/llama-server"));
    }

    #[test]
    fn missing_binary_is_an_error() {
        let e = find_binary(&cfg(), Some("/usr/bin"), &|_| false).unwrap_err();
        assert_eq!(e, OcrError::BinaryMissing);

        let mut c = cfg();
        c.binary = Some(PathBuf::from("/nope/llama-server"));
        assert_eq!(
            find_binary(&c, None, &|_| false).unwrap_err(),
            OcrError::BinaryMissing
        );
    }

    #[test]
    fn free_port_is_usable_and_nonzero() {
        let p = free_port().unwrap();
        assert!(p > 0);
        // Binding it again must succeed: the probe socket has been dropped.
        assert!(std::net::TcpListener::bind(("127.0.0.1", p)).is_ok());
    }

    /// The idle rule is arithmetic on an injected `now`, so it needs no
    /// process and no sleeping.
    #[test]
    fn idle_expiry_is_measured_from_the_last_use() {
        let idle = Duration::from_secs(300);
        let last_used = Instant::now();
        let at = |elapsed: Duration| last_used + elapsed;
        assert!(!expired(last_used, idle, at(Duration::from_secs(299))));
        assert!(expired(last_used, idle, at(Duration::from_secs(300))));
        assert!(expired(last_used, idle, at(Duration::from_secs(3600))));
    }

    /// The reaper must never win a race against an in-flight request: a busy
    /// child is never reaped no matter how idle-expired it looks, because
    /// `last_used` is only bumped once the request finishes.
    #[test]
    fn busy_child_is_never_reaped_even_when_idle_expired() {
        let idle = Duration::from_secs(300);
        let last_used = Instant::now();
        let long_after = last_used + Duration::from_secs(3600);
        assert!(!should_reap(true, last_used, idle, long_after));
        assert!(should_reap(false, last_used, idle, long_after));
        assert!(!should_reap(false, last_used, idle, last_used));
    }

    /// Pushing more lines than the cap must keep only the most recent ones,
    /// in order, with no process involved.
    #[test]
    fn output_tail_keeps_only_the_most_recent_lines() {
        let tail = OutputTail::default();
        for i in 0..(TAIL_CAPACITY + 10) {
            tail.push(format!("line {i}"));
        }
        let snapshot = tail.snapshot();
        let lines: Vec<&str> = snapshot.lines().collect();
        assert_eq!(lines.len(), TAIL_CAPACITY);
        assert_eq!(lines.first(), Some(&"line 10"));
        assert_eq!(
            lines.last().copied(),
            Some(format!("line {}", TAIL_CAPACITY + 9)).as_deref()
        );
    }
}