Skip to main content

optimization_runner/mcp/
mod.rs

1//! `optimization-mcp`: a Model Context Protocol server over one node root.
2//!
3//! The server speaks MCP over stdio, one JSON-RPC message per line. It is
4//! dual-era: requests that carry `io.modelcontextprotocol/protocolVersion`
5//! in `_meta` are served statelessly under revision 2026-07-28, with the
6//! Tasks extension (`io.modelcontextprotocol/tasks`); an `initialize`
7//! request selects a legacy revision (2025-11-25 and earlier) for the
8//! process. Every tool drives the `optimization-run` command line, the
9//! runner's documented interface, so the runner's validation, idempotency,
10//! admission and recovery rules apply unchanged. The server registers no
11//! workers and initializes no node: that stays with the person who owns the
12//! node.
13//!
14//! See the guide's section [Agents and MCP](https://github.com/dietmarwo/optimization-jobs/blob/main/docs/job-api.md#agents-and-mcp) for the tools
15//! and their mapping onto the runner.
16mod guide;
17mod inputs;
18mod tasks;
19mod tools;
20
21use clap::{Parser, ValueEnum};
22use serde_json::{Map, Value, json};
23use std::{
24    collections::HashMap,
25    io::{self, BufRead, Read, Write},
26    path::PathBuf,
27    sync::{
28        Arc, Condvar, Mutex,
29        atomic::{AtomicBool, AtomicUsize, Ordering},
30    },
31    thread,
32    time::Duration,
33};
34
35/// Protocol revisions served statelessly, with per-request `_meta`.
36const MODERN: [&str; 1] = ["2026-07-28"];
37/// Protocol revisions served after an `initialize` handshake, newest first.
38const LEGACY: [&str; 4] = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
39const PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
40const CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
41const SERVER_INFO: &str = "io.modelcontextprotocol/serverInfo";
42const SUBSCRIPTION: &str = "io.modelcontextprotocol/subscriptionId";
43/// The Tasks extension (SEP-2663).
44const TASKS: &str = "io.modelcontextprotocol/tasks";
45/// MCP error codes of revision 2026-07-28.
46const MISSING_CAPABILITY: i64 = -32021;
47const UNSUPPORTED_VERSION: i64 = -32022;
48const INVALID_PARAMS: i64 = -32602;
49const METHOD_NOT_FOUND: i64 = -32601;
50const INVALID_REQUEST: i64 = -32600;
51const PARSE_ERROR: i64 = -32700;
52const INTERNAL_ERROR: i64 = -32603;
53/// The server is at one of its limits below; the request may be retried.
54const SERVER_BUSY: i64 = -32000;
55/// Largest message, in bytes: the input files of a job are files, not part
56/// of it. A longer line is skipped unread and answered with an error.
57const MAX_MESSAGE: usize = 64 * 1024 * 1024;
58/// Requests answered at the same time (each runs on a thread of its own).
59const MAX_REQUESTS: usize = 64;
60/// Of these, requests that wait (`wait_job`, `subscriptions/listen`): the
61/// rest stays free for status, cancellation and other short calls.
62const MAX_WAITING: usize = 32;
63/// Calls that run worker validation (`validate_job`, `submit_job`) at the
64/// same time; further ones queue. Validation runs before CPU-slot admission.
65const MAX_VALIDATIONS: usize = 4;
66/// How long clients may cache `tools/list` and `server/discover`.
67const CACHE_MS: u64 = 3_600_000;
68
69const INSTRUCTIONS: &str = "Runs durable optimization jobs on this node with its registered native \
70workers (fcmaes, LP-IP, SQP and application workers). If no solver or profile has been chosen \
71yet, call get_guide first: it says which solver and profile fit the problem (its section \
72argument returns one part). Then call describe_node, and describe_worker for a worker's profiles \
73and options, the JSON Schemas of its payloads and runnable examples. Write an \
74optimization.job/0.1 envelope, check it with validate_job and start it with submit_job. Input \
75files that are not on this machine yet, such as a new LP model, go through put_input, which \
76returns the file, sha256 and input_dir for the job. The request_key makes \
77submission idempotent: the same key with the same content returns the existing job, other \
78content under that key is rejected, so choose a new key for a new job. Jobs run detached from \
79this server and survive its restart. Follow a job with wait_job or get_job and read get_result \
80when it has ended. cancel_job stops it gracefully and keeps completed work; kill_job stops it \
81at once. Every task result carries a claim (what the worker asserts) and evidence (how much of \
82it was independently rechecked); there is no automatic winner across tasks or jobs.";
83
84#[derive(Parser)]
85#[command(
86    name = "optimization-mcp",
87    version,
88    about = "MCP server (stdio) for the durable optimization jobs of one optimization-run node (Linux)"
89)]
90struct Args {
91    /// Node root, as for optimization-run.
92    #[arg(
93        long,
94        env = "OPTIMIZATION_RUN_ROOT",
95        default_value = ".optimization-jobs"
96    )]
97    root: PathBuf,
98    /// The optimization-run executable; by default the one next to this
99    /// server.
100    #[arg(long)]
101    runner: Option<PathBuf>,
102    /// How submit_job starts jobs: `process` runs `optimization-run run` in a
103    /// session of its own, which outlives this server; `systemd` uses
104    /// `optimization-run submit` (a systemd user manager is required).
105    #[arg(long, value_enum, default_value_t = Launch::Process)]
106    launch: Launch,
107    /// Directory that relative input files of inline jobs are read from, by
108    /// default the working directory.
109    #[arg(long)]
110    input_dir: Option<PathBuf>,
111    /// Largest total size of the input store of put_input (NODE/mcp/inputs),
112    /// in bytes.
113    #[arg(long, default_value_t = inputs::DEFAULT_STORE_BYTES)]
114    input_store_bytes: u64,
115}
116
117#[derive(Clone, Copy, Debug, PartialEq, ValueEnum)]
118pub enum Launch {
119    Process,
120    Systemd,
121}
122
123impl Launch {
124    pub fn name(self) -> &'static str {
125        match self {
126            Launch::Process => "process",
127            Launch::Systemd => "systemd",
128        }
129    }
130}
131
132pub struct Server {
133    pub root: PathBuf,
134    pub runner: PathBuf,
135    pub launch: Launch,
136    pub input_dir: PathBuf,
137    /// Limit of the input store's total size.
138    pub input_store_bytes: u64,
139    out: Mutex<io::Stdout>,
140    inflight: Mutex<HashMap<String, Arc<AtomicBool>>>,
141    initialized: AtomicBool,
142    /// JSON-RPC batches, part of protocol 2025-03-26 only.
143    batches: AtomicBool,
144    pub shutdown: AtomicBool,
145    /// Requests counted against [`MAX_WAITING`].
146    waiting: AtomicUsize,
147    /// Running validations and the signal that one ended.
148    validations: (Mutex<usize>, Condvar),
149}
150
151/// One of the `MAX_VALIDATIONS` validation places, given back on drop.
152pub struct Permit<'a>(&'a Server);
153
154impl Drop for Permit<'_> {
155    fn drop(&mut self) {
156        let (count, ended) = &self.0.validations;
157        *count.lock().unwrap_or_else(|e| e.into_inner()) -= 1;
158        ended.notify_one();
159    }
160}
161
162/// One request: its era and whether it may be cancelled or report progress.
163pub struct Ctx {
164    pub modern: bool,
165    /// The client declared the Tasks extension on this request.
166    pub tasks: bool,
167    pub cancel: Arc<AtomicBool>,
168    pub progress: Option<Value>,
169    pub id: Value,
170}
171
172pub enum Reply {
173    Ok(Value),
174    Err(i64, String, Option<Value>),
175    /// No response: the request was cancelled, or it ended a subscription
176    /// the client cancelled.
177    Silent,
178}
179
180impl Ctx {
181    pub fn stopped(&self, server: &Server) -> bool {
182        self.cancel.load(Ordering::Relaxed) || server.shutdown.load(Ordering::Relaxed)
183    }
184}
185
186fn supported() -> Vec<&'static str> {
187    MODERN.iter().chain(LEGACY.iter()).copied().collect()
188}
189
190fn server_info() -> Value {
191    json!({"name":"optimization-mcp","title":"Optimization jobs","version":env!("CARGO_PKG_VERSION")})
192}
193
194fn missing_tasks_capability() -> Reply {
195    Reply::Err(
196        MISSING_CAPABILITY,
197        "Missing required client capability".into(),
198        Some(json!({"requiredCapabilities":{"extensions":{TASKS:{}}}})),
199    )
200}
201
202/// The protocol error of a task whose job cannot be read or cancelled. A job
203/// removed from the node makes its task unknown.
204fn job_error(job_id: &str, action: &str, e: &tools::ToolError) -> Reply {
205    if e.code == "unknown_job" {
206        return Reply::Err(
207            INVALID_PARAMS,
208            format!("Failed to retrieve task: its job {job_id} no longer exists on this node"),
209            None,
210        );
211    }
212    Reply::Err(
213        INTERNAL_ERROR,
214        format!("cannot {action} job {job_id}: {}: {}", e.code, e.message),
215        None,
216    )
217}
218
219impl Server {
220    /// Waits for a validation place; a cancelled request stops waiting.
221    pub fn validation_permit(&self, ctx: &Ctx) -> Result<Permit<'_>, tools::Fail> {
222        let (count, ended) = &self.validations;
223        let mut running = count.lock().unwrap_or_else(|e| e.into_inner());
224        while *running >= MAX_VALIDATIONS {
225            if ctx.stopped(self) {
226                return Err(tools::Fail::Cancelled);
227            }
228            running = ended
229                .wait_timeout(running, Duration::from_millis(100))
230                .unwrap_or_else(|e| e.into_inner())
231                .0;
232        }
233        *running += 1;
234        Ok(Permit(self))
235    }
236
237    /// Writes one message as one line; a closed stdout ends the server.
238    pub fn send(&self, message: &Value) {
239        let mut out = self.out.lock().unwrap_or_else(|e| e.into_inner());
240        let ok = serde_json::to_writer(&mut *out, message).is_ok()
241            && out.write_all(b"\n").is_ok()
242            && out.flush().is_ok();
243        if !ok {
244            std::process::exit(0);
245        }
246    }
247
248    pub fn notify(&self, method: &str, params: Value) {
249        self.send(&json!({"jsonrpc":"2.0","method":method,"params":params}));
250    }
251
252    /// Reports `progress` of `total` for a request that asked for progress.
253    pub fn progress(&self, ctx: &Ctx, progress: u64, total: Option<u64>, message: &str) {
254        if let Some(token) = &ctx.progress {
255            let mut params = json!({"progressToken":token,"progress":progress,"message":message});
256            if let Some(total) = total {
257                params["total"] = json!(total);
258            }
259            self.notify("notifications/progress", params);
260        }
261    }
262
263    /// The response to a request, if it gets one.
264    fn finish(&self, id: &Value, cancel: &AtomicBool, reply: Reply, modern: bool) -> Option<Value> {
265        self.inflight
266            .lock()
267            .unwrap_or_else(|e| e.into_inner())
268            .remove(&id.to_string());
269        // A cancelled request gets no response at all.
270        if cancel.load(Ordering::Relaxed) {
271            return None;
272        }
273        Some(match reply {
274            Reply::Silent => return None,
275            Reply::Ok(mut result) => {
276                if modern {
277                    let object = result.as_object_mut().expect("results are objects");
278                    object
279                        .entry("resultType")
280                        .or_insert_with(|| json!("complete"));
281                    let meta = object.entry("_meta").or_insert_with(|| json!({}));
282                    meta[SERVER_INFO] = server_info();
283                }
284                json!({"jsonrpc":"2.0","id":id,"result":result})
285            }
286            Reply::Err(code, message, data) => {
287                let mut error = json!({"code":code,"message":message});
288                if let Some(data) = data {
289                    error["data"] = data;
290                }
291                json!({"jsonrpc":"2.0","id":id,"error":error})
292            }
293        })
294    }
295
296    /// Decides how a request is served: `(modern, tasks)`, or the error that
297    /// rejects it.
298    fn era(&self, method: &str, params: &Value) -> Result<(bool, bool), Reply> {
299        let meta = &params["_meta"];
300        if !meta[PROTOCOL_VERSION].is_null() {
301            if !meta[PROTOCOL_VERSION]
302                .as_str()
303                .is_some_and(|v| MODERN.contains(&v))
304            {
305                return Err(Reply::Err(
306                    UNSUPPORTED_VERSION,
307                    format!(
308                        "Unsupported protocol version: {} is served per request; {} only after initialize, without _meta",
309                        MODERN.join(", "),
310                        LEGACY.join(", ")
311                    ),
312                    Some(json!({"supported":supported(),"requested":meta[PROTOCOL_VERSION]})),
313                ));
314            }
315            if !meta[CLIENT_CAPABILITIES].is_object() {
316                return Err(Reply::Err(
317                    INVALID_PARAMS,
318                    format!("_meta lacks {CLIENT_CAPABILITIES}"),
319                    None,
320                ));
321            }
322            let tasks = meta[CLIENT_CAPABILITIES]["extensions"][TASKS].is_object();
323            return Ok((true, tasks));
324        }
325        if method == "initialize" || method == "ping" || self.initialized.load(Ordering::Relaxed) {
326            return Ok((false, false));
327        }
328        Err(Reply::Err(
329            INVALID_PARAMS,
330            format!(
331                "request lacks _meta {PROTOCOL_VERSION}: this server serves {} per request, and {} after initialize",
332                MODERN.join(", "),
333                LEGACY.join(", ")
334            ),
335            None,
336        ))
337    }
338
339    /// Serves one request and returns its response, if any. A panic is a
340    /// bug, but it still answers the request.
341    fn request(
342        self: &Arc<Self>,
343        id: Value,
344        method: String,
345        params: Value,
346        cancel: Arc<AtomicBool>,
347    ) -> Option<Value> {
348        let (reply, modern) = match self.era(&method, &params) {
349            Err(reply) => (reply, false),
350            Ok((modern, tasks)) => {
351                let ctx = Ctx {
352                    modern,
353                    tasks,
354                    progress: params["_meta"].get("progressToken").cloned(),
355                    cancel: cancel.clone(),
356                    id: id.clone(),
357                };
358                let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
359                    self.dispatch(&method, &params, &ctx)
360                }))
361                .unwrap_or_else(|_| {
362                    Reply::Err(
363                        INTERNAL_ERROR,
364                        "internal error of optimization-mcp; its stderr has the details".into(),
365                        None,
366                    )
367                });
368                (reply, modern)
369            }
370        };
371        self.finish(&id, &cancel, reply, modern)
372    }
373
374    fn dispatch(&self, method: &str, params: &Value, ctx: &Ctx) -> Reply {
375        match (ctx.modern, method) {
376            (true, "server/discover") => Reply::Ok(json!({
377                "supportedVersions": supported(),
378                "capabilities": {"tools": {}, "extensions": {TASKS: {}}},
379                "instructions": INSTRUCTIONS,
380                "ttlMs": CACHE_MS,
381                "cacheScope": "public",
382            })),
383            (false, "initialize") => {
384                let version = params["protocolVersion"]
385                    .as_str()
386                    .filter(|v| LEGACY.contains(v))
387                    .unwrap_or(LEGACY[0]);
388                self.initialized.store(true, Ordering::Relaxed);
389                self.batches
390                    .store(version == "2025-03-26", Ordering::Relaxed);
391                Reply::Ok(json!({
392                    "protocolVersion": version,
393                    "capabilities": {"tools": {"listChanged": false}},
394                    "serverInfo": server_info(),
395                    "instructions": INSTRUCTIONS,
396                }))
397            }
398            (false, "ping") => Reply::Ok(json!({})),
399            (_, "tools/list") => {
400                let mut result = json!({"tools": tools::definitions()});
401                if ctx.modern {
402                    result["ttlMs"] = json!(CACHE_MS);
403                    result["cacheScope"] = json!("public");
404                }
405                Reply::Ok(result)
406            }
407            (_, "tools/call") => self.call_tool(params, ctx),
408            (true, "tasks/get" | "tasks/update" | "tasks/cancel") => {
409                if !ctx.tasks {
410                    return missing_tasks_capability();
411                }
412                self.task_method(method, params, ctx)
413            }
414            (true, "subscriptions/listen") => self.listen(params, ctx),
415            _ => Reply::Err(
416                METHOD_NOT_FOUND,
417                format!("Method not found: {method}"),
418                None,
419            ),
420        }
421    }
422
423    fn call_tool(&self, params: &Value, ctx: &Ctx) -> Reply {
424        let Some(name) = params["name"].as_str() else {
425            return Reply::Err(INVALID_PARAMS, "tools/call needs a tool name".into(), None);
426        };
427        let arguments = match &params["arguments"] {
428            Value::Null => json!({}),
429            Value::Object(_) => params["arguments"].clone(),
430            _ => {
431                return Reply::Err(
432                    INVALID_PARAMS,
433                    "tool arguments must be an object".into(),
434                    None,
435                );
436            }
437        };
438        if !tools::exists(name) {
439            return Reply::Err(INVALID_PARAMS, format!("Unknown tool: {name}"), None);
440        }
441        match tools::call(self, name, &arguments, ctx) {
442            tools::Outcome::Done(value) => Reply::Ok(tools::tool_result(value, false)),
443            tools::Outcome::Failed(error) => Reply::Ok(tools::tool_result(error.value(), true)),
444            tools::Outcome::Task(task) => Reply::Ok(task),
445            tools::Outcome::Cancelled => Reply::Silent,
446        }
447    }
448
449    fn task_method(&self, method: &str, params: &Value, ctx: &Ctx) -> Reply {
450        let Some(task_id) = params["taskId"].as_str() else {
451            return Reply::Err(INVALID_PARAMS, "taskId must be a string".into(), None);
452        };
453        let job_id = match tasks::job_of(&self.root, task_id) {
454            Ok(Some(job)) => job,
455            Ok(None) => {
456                return Reply::Err(
457                    INVALID_PARAMS,
458                    "Failed to retrieve task: Task not found".into(),
459                    None,
460                );
461            }
462            Err(e) => return Reply::Err(INTERNAL_ERROR, format!("task store: {e}"), None),
463        };
464        match method {
465            "tasks/get" => match tasks::detailed(self, task_id, &job_id, ctx) {
466                Ok(task) => Reply::Ok(task),
467                Err(tools::Fail::Cancelled) => Reply::Silent,
468                Err(tools::Fail::Tool(e)) => job_error(&job_id, "read", &e),
469            },
470            // No task of this server asks for input; responses are ignored.
471            "tasks/update" => Reply::Ok(json!({})),
472            _ => match tools::cancel(self, &job_id, false) {
473                Ok(_) => Reply::Ok(json!({})),
474                // A job that already ended has nothing to cancel; the
475                // acknowledgement promises no transition.
476                Err(tools::Fail::Tool(e)) if e.code == "already_terminal" => Reply::Ok(json!({})),
477                Err(tools::Fail::Cancelled) => Reply::Silent,
478                Err(tools::Fail::Tool(e)) => job_error(&job_id, "cancel", &e),
479            },
480        }
481    }
482
483    /// `subscriptions/listen`: task status notifications for `taskIds`. The
484    /// server sends no other notification type; the stream stays open until
485    /// the client cancels it.
486    fn listen(&self, params: &Value, ctx: &Ctx) -> Reply {
487        let Some(filter) = params["notifications"].as_object() else {
488            return Reply::Err(
489                INVALID_PARAMS,
490                "subscriptions/listen needs a notifications object".into(),
491                None,
492            );
493        };
494        let wanted = filter.get("taskIds");
495        if wanted.is_some() && !ctx.tasks {
496            return missing_tasks_capability();
497        }
498        let mut tracked: Vec<(String, String)> = vec![];
499        if let Some(ids) = wanted {
500            let Some(ids) = ids.as_array() else {
501                return Reply::Err(INVALID_PARAMS, "taskIds must be an array".into(), None);
502            };
503            for id in ids.iter().filter_map(Value::as_str) {
504                if let Ok(Some(job)) = tasks::job_of(&self.root, id)
505                    && !tracked.iter().any(|(t, _)| t == id)
506                {
507                    tracked.push((id.to_owned(), job));
508                }
509            }
510        }
511        let mut agreed = Map::new();
512        if wanted.is_some() {
513            agreed.insert(
514                "taskIds".into(),
515                json!(tracked.iter().map(|(t, _)| t).collect::<Vec<_>>()),
516            );
517        }
518        self.notify(
519            "notifications/subscriptions/acknowledged",
520            json!({"_meta":{SUBSCRIPTION:ctx.id},"notifications":agreed}),
521        );
522        let mut last: HashMap<String, String> = HashMap::new();
523        while !ctx.stopped(self) {
524            tracked.retain(|(task_id, job_id)| {
525                let Ok(mut task) = tasks::detailed(self, task_id, job_id, ctx) else {
526                    return true;
527                };
528                let status = task["status"].as_str().unwrap_or_default().to_owned();
529                if last.get(task_id) != Some(&status) {
530                    if let Some(object) = task.as_object_mut() {
531                        object.remove("resultType");
532                        object.insert("_meta".into(), json!({SUBSCRIPTION:ctx.id}));
533                    }
534                    self.notify("notifications/tasks", task);
535                    last.insert(task_id.clone(), status.clone());
536                }
537                !tasks::terminal_status(&status)
538            });
539            tools::pause(self, ctx, tasks::POLL);
540        }
541        Reply::Silent
542    }
543
544    fn notification(&self, method: &str, params: &Value) {
545        if method == "notifications/cancelled" {
546            let id = params["requestId"].to_string();
547            if let Some(flag) = self
548                .inflight
549                .lock()
550                .unwrap_or_else(|e| e.into_inner())
551                .get(&id)
552            {
553                flag.store(true, Ordering::Relaxed);
554            }
555        }
556        // notifications/initialized and anything else need no action.
557    }
558
559    fn error(id: Value, code: i64, message: &str) -> Value {
560        json!({"jsonrpc":"2.0","id":id,"error":{"code":code,"message":message}})
561    }
562
563    fn busy(id: Value, message: String) -> Value {
564        json!({"jsonrpc":"2.0","id":id,"error":{"code":SERVER_BUSY,"message":message,
565            "data":{"retryable":true}}})
566    }
567
568    /// Starts one message of the input: a request runs on a thread of its
569    /// own and yields its response through the handle; a notification or a
570    /// client's response yields nothing.
571    fn accept(self: &Arc<Self>, message: Value) -> Option<thread::JoinHandle<Option<Value>>> {
572        let method = message["method"].as_str().map(str::to_owned);
573        let params = message.get("params").cloned().unwrap_or(json!({}));
574        let immediate = |reply: Value| Some(thread::spawn(move || Some(reply)));
575        match (method, message.get("id")) {
576            // Responses from the client: this server sends no requests.
577            (None, _) if message.is_object() && message.get("id").is_some() => None,
578            (Some(method), None) if message.is_object() => {
579                self.notification(&method, &params);
580                None
581            }
582            (Some(method), Some(id)) if id.is_string() || id.is_number() => {
583                let cancel = Arc::new(AtomicBool::new(false));
584                let waits = method == "subscriptions/listen"
585                    || (method == "tools/call" && params["name"] == "wait_job");
586                {
587                    let mut inflight = self.inflight.lock().unwrap_or_else(|e| e.into_inner());
588                    if inflight.contains_key(&id.to_string()) {
589                        // Answering under that ID would give it two responses.
590                        eprintln!("optimization-mcp: request id {id} is already in use");
591                        return immediate(Self::error(
592                            Value::Null,
593                            INVALID_REQUEST,
594                            &format!("request id {id} is already in use"),
595                        ));
596                    }
597                    if inflight.len() >= MAX_REQUESTS {
598                        return immediate(Self::busy(
599                            id.clone(),
600                            format!(
601                                "server busy: {MAX_REQUESTS} requests in progress; retry later"
602                            ),
603                        ));
604                    }
605                    if waits && self.waiting.fetch_add(1, Ordering::Relaxed) >= MAX_WAITING {
606                        self.waiting.fetch_sub(1, Ordering::Relaxed);
607                        return immediate(Self::busy(
608                            id.clone(),
609                            format!(
610                                "server busy: {MAX_WAITING} waiting requests (wait_job, subscriptions/listen) in progress; retry later"
611                            ),
612                        ));
613                    }
614                    inflight.insert(id.to_string(), cancel.clone());
615                }
616                let server = self.clone();
617                let id = id.clone();
618                Some(thread::spawn(move || {
619                    let response = server.request(id, method, params, cancel);
620                    if waits {
621                        server.waiting.fetch_sub(1, Ordering::Relaxed);
622                    }
623                    response
624                }))
625            }
626            _ => immediate(Self::error(Value::Null, INVALID_REQUEST, "Invalid request")),
627        }
628    }
629
630    fn serve(self: Arc<Self>) {
631        let mut input = io::stdin().lock();
632        let mut line = Vec::new();
633        loop {
634            match read_message(&mut input, &mut line) {
635                Ok(Frame::End) | Err(_) => break,
636                Ok(Frame::TooLong) => {
637                    self.send(&Self::error(
638                        Value::Null,
639                        INVALID_REQUEST,
640                        &format!("message longer than {MAX_MESSAGE} bytes; skipped"),
641                    ));
642                    continue;
643                }
644                Ok(Frame::Message) => {}
645            }
646            if line.iter().all(u8::is_ascii_whitespace) {
647                continue;
648            }
649            let message: Value = match serde_json::from_slice(&line) {
650                Ok(message) => message,
651                Err(e) => {
652                    self.send(&Self::error(
653                        Value::Null,
654                        PARSE_ERROR,
655                        &format!("Parse error: {e}"),
656                    ));
657                    continue;
658                }
659            };
660            match message {
661                // A JSON-RPC batch (protocol 2025-03-26): one array of the
662                // responses, sent when all of them are ready, so a stream
663                // that never ends cannot be part of one.
664                Value::Array(messages)
665                    if !messages.is_empty() && self.batches.load(Ordering::Relaxed) =>
666                {
667                    let handles: Vec<_> = messages
668                        .into_iter()
669                        .filter_map(|m| {
670                            if m["method"] == "subscriptions/listen" {
671                                let id = m.get("id").cloned().unwrap_or(Value::Null);
672                                let reply = Self::error(
673                                    id,
674                                    INVALID_REQUEST,
675                                    "subscriptions/listen cannot be part of a batch",
676                                );
677                                return Some(thread::spawn(move || Some(reply)));
678                            }
679                            self.accept(m)
680                        })
681                        .collect();
682                    let server = self.clone();
683                    thread::spawn(move || {
684                        let responses: Vec<Value> = handles
685                            .into_iter()
686                            .filter_map(|h| h.join().ok().flatten())
687                            .collect();
688                        if !responses.is_empty() {
689                            server.send(&Value::Array(responses));
690                        }
691                    });
692                }
693                Value::Array(messages) => self.send(&Self::error(
694                    Value::Null,
695                    INVALID_REQUEST,
696                    if messages.is_empty() {
697                        "empty batch"
698                    } else {
699                        "JSON-RPC batches are part of protocol 2025-03-26 only; initialize with it to send them"
700                    },
701                )),
702                message => {
703                    if let Some(handle) = self.accept(message) {
704                        let server = self.clone();
705                        thread::spawn(move || {
706                            if let Ok(Some(response)) = handle.join() {
707                                server.send(&response);
708                            }
709                        });
710                    }
711                }
712            }
713        }
714        // End of input is the stdio shutdown signal. Jobs keep running.
715        self.shutdown.store(true, Ordering::Relaxed);
716    }
717}
718
719enum Frame {
720    Message,
721    TooLong,
722    End,
723}
724
725/// Reads one line of at most [`MAX_MESSAGE`] bytes into `line`. The rest of
726/// a longer line is consumed without being kept.
727fn read_message(input: &mut impl BufRead, line: &mut Vec<u8>) -> io::Result<Frame> {
728    line.clear();
729    if input
730        .by_ref()
731        .take(MAX_MESSAGE as u64 + 1)
732        .read_until(b'\n', line)?
733        == 0
734    {
735        return Ok(Frame::End);
736    }
737    if line.len() <= MAX_MESSAGE || line.ends_with(b"\n") {
738        return Ok(Frame::Message);
739    }
740    line.clear();
741    line.shrink_to(1 << 16);
742    loop {
743        let buffer = input.fill_buf()?;
744        if buffer.is_empty() {
745            return Ok(Frame::TooLong);
746        }
747        match buffer.iter().position(|&b| b == b'\n') {
748            Some(end) => {
749                input.consume(end + 1);
750                return Ok(Frame::TooLong);
751            }
752            None => {
753                let all = buffer.len();
754                input.consume(all);
755            }
756        }
757    }
758}
759
760pub fn main() {
761    if !cfg!(target_os = "linux") {
762        eprintln!("optimization-mcp: Linux is required");
763        std::process::exit(2);
764    }
765    let args = Args::parse();
766    let fail = |message: String| -> ! {
767        eprintln!("optimization-mcp: {message}");
768        std::process::exit(2)
769    };
770    let runner = args.runner.unwrap_or_else(|| {
771        std::env::current_exe()
772            .ok()
773            .and_then(|exe| exe.parent().map(|dir| dir.join("optimization-run")))
774            .unwrap_or_else(|| PathBuf::from("optimization-run"))
775    });
776    let runner = std::fs::canonicalize(&runner)
777        .unwrap_or_else(|e| fail(format!("runner {}: {e}", runner.display())));
778    if let Err(e) = std::fs::create_dir_all(&args.root) {
779        fail(format!("node root {}: {e}", args.root.display()));
780    }
781    let root = std::fs::canonicalize(&args.root)
782        .unwrap_or_else(|e| fail(format!("node root {}: {e}", args.root.display())));
783    let input_dir = args
784        .input_dir
785        .map_or_else(std::env::current_dir, Ok)
786        .and_then(std::fs::canonicalize)
787        .unwrap_or_else(|e| fail(format!("input directory: {e}")));
788    tools::clean_staging(&root);
789    inputs::clean(&root);
790    eprintln!(
791        "optimization-mcp {}: node {}, runner {}, launch {}",
792        env!("CARGO_PKG_VERSION"),
793        root.display(),
794        runner.display(),
795        args.launch.name()
796    );
797    let server = Arc::new(Server {
798        root,
799        runner,
800        launch: args.launch,
801        input_dir,
802        input_store_bytes: args.input_store_bytes,
803        out: Mutex::new(io::stdout()),
804        inflight: Mutex::new(HashMap::new()),
805        initialized: AtomicBool::new(false),
806        batches: AtomicBool::new(false),
807        shutdown: AtomicBool::new(false),
808        waiting: AtomicUsize::new(0),
809        validations: (Mutex::new(0), Condvar::new()),
810    });
811    server.serve();
812}